如何添加回调到未来在Scala? [英] How to add callbacks to Future in Scala?

查看:187
本文介绍了如何添加回调到未来在Scala?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这里的示例:


val fut = Future { ... // my body function } // my body function starts here
fut onComplete { ... // my callback }

看起来我可以在之后添加回调完成我的身体功能。它仍然被调用吗?无论如何,我想在我的功能开始运行之前添加回调到未来。是否有意义 ?

Looks like I may add the callback after the completion of my body function. Is it still invoked ? Anyway, I would prefer to add callbacks to a future before my function starts running. Does it make sense ? How can I do that ?

推荐答案

如果你想控制未来的执行点,你可以链接它 Promise

If you want to control the point of execution of a future, you could chain it with a Promise.

import scala.concurrent._
import ExecutionContext.Implicits.global

val initialPromise = promise[Unit]

// add your computations
val fut = initialPromise.future map { _ => println("My Future") }

// register callbacks
fut onComplete { _ => println("My Callback") }

// run
initialPromise.success()

使用除 Unit 以外的其他东西可以让计算输入任意值。

Using something other than Unit allows you to feed the computation with arbitrary values.

这篇关于如何添加回调到未来在Scala?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆