bbarker
bbarker

Reputation: 13088

Is there a canonical or good way to define a non-busy-wait Future in Scala that never ends?

I need to define a mutable Future used as a UI callback. When created, it shouldn't complete until it is assigned an actual computation, so something like this:

var myCallback: Future[Option[Long]] = Future.dummyWait

Of course, I could do the following, but that would be a busy wait:

var myCallback: Future[Option[Long]] = Future{while(true){0;}; Some(0L)}

If Future isn't the right abstraction, what is?

Upvotes: 1

Views: 116

Answers (1)

OlivierBlanvillain
OlivierBlanvillain

Reputation: 7768

The correct abstraction for a to be completed Future is a Promise:

val p = Promise[Option[Long]]()
val myCallback: Future[Option[Long]] = p.future

// Somewhere else in your code, this can trigger myCallback completion:
p.success(Some(42L))

Upvotes: 2

Related Questions