Reputation: 13560
I'm using the dart:async
library to do some data processing. I'm adding objects to a StreamController
and another module is listening to the stream. Now I want, that the other module is returning a result of the processing back to the add
call (as a future).
Here is some example code that should illustrate what I want to do (It doesn't work, because the add method doesn't return a future):
final controller = new StreamController();
controller.stream.listen((a) {
// Do something with a, after that return something:
return 42;
});
final aFuture = controller.add(new A());
aFuture.then((result) {
// result == 42
});
Is something like this possible with dart:async
, another library, or do I need to write my own classes?
PS: An alternative would be the following, but it would be 'more complicated' to use that a simple return:
final controller = new StreamController();
controller.stream.listen((container) {
// Do something with container.a, after that return something:
container.completer.complete(42);
});
final completer = new Completer();
controller.add(new Container(new A(), completer));
completer.future.then((result) {
// result == 42
});
Upvotes: 0
Views: 292
Reputation: 83
You could use a wrapper around the StreamController like:
class StreamControllerWrapper{
MessageBox mb;
StreamController controller;
StreamControllerWrapper(this.controller){
mb = new MessageBox();
controller.stream.listen((a) {
var replyTo = a['replyTo'];
// Do something with a, after that return something:
replyTo.add(42);
});
}
Future add(msg){
Completer c = new Completer();
mb.stream.listen((reply){
c.complete(reply);
});
controller.add({'content':msg, 'replyTo':mb.sink});
return c.future;
}
}
And then invoke the behavior like this:
final controllerWrapper = new StreamControllerWrapper(new StreamController());
controllerWrapper.add(new A())
.then((result){
print(result);
});
Upvotes: 1