initializing a Promise (Scala)
I've been fairly comfortable with the general notion of Promises from other languages (mainly Java and JavaScript) for a while now (possibly misguidedly so, I suppose), but when tinkering with the Promise API in Scala, I banged my head on a "style" problem I've not yet managed to resolve (no pun intended!), and to be fair, I don't know if I "should" resolve it.
My concern relates to use of promise/future to handle a repeating (eg event-like) situation. Here's the code (sorry it's kinda big considering the tiny part of it that matters, but I'm not sure how to discuss this clearly without a concrete example.
import javax.swing._
import scala.concurrent.Promise
object PromGui {
def main(args: Array[String]): Unit = {
import scala.concurrent.ExecutionContext.Implicits.global
var promise = Promise[String] // VAR?? really?
promise
.future
.map(s => s"The initial value is $s")
.foreach(Console.err.println)
val f = new JFrame("My Frame")
val p = new JPanel()
val t = new JTextField()
val b = new JButton("Press me!")
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS))
f.setContentPane(p)
p add t
p add b
b.addActionListener( e => {
promise.success(t.getText)
promise = Promise[String] // var because this needs to update it
promise.future
.map(s => s"The subsequent value is $s")
.foreach(Console.err.println)
})
f.setSize(400, 200)
f.setVisible(true)
}
}
Now, the thing that bothers me is that " var promise
" at the second line inside the main method. It seems to me that Promises/Futures are a somewhat "FP" kind of concept (the promise pipeline being a monadic-like thing and all, and the flatmap and variations being higher order functions). But I cannot for the life of me (and I might well be getting nicely set up for a good self-kicking if you show me how simple this really is) see how to get the promise to "reset" without creating a new one, and if I have to create a new one, I cannot see how to interact with it without using a mutable variable.
So, I guess the real question is, what's the elegant way to construct code that handles a cyclic type occurrence using promise/future?
EDIT:
I realize I represented this question poorly at the outset. I don't want to "re-trigger" the original Promise, I want to allow the conclusion of processing of a Promise to configure/setup a new one. That, of itself isn't hard, but I was hoping to find a structure that allowed me to do this without using a "var". It feels like there "ought" to be a construct that would let me create the new Promise, and therefore the reference to it, in something closure-like. But I'm not seeing it, and it seems others aren't either, so maybe this is just a dead end question.
You can't uncomplete a Promise
or a Future
. You're probably looking for something like Observable
, Rx
, Var
, ... from Scala.rx or RxScala.
上一篇: 回调和承诺有什么区别
下一篇: 初始化Promise(Scala)