我正在使用dart:async
库进行一些数据处理。我正在向StreamController
添加对象,而另一个模块正在侦听流。现在我想,另一个模块正在将处理结果返回到add
调用(作为未来)。
下面是一些示例代码,应该说明我想要做什么(它不起作用,因为add方法不会返回未来):
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
});
dart:async
,另一个库是否可以这样,或者我需要编写自己的类?
PS:替代方案如下,但使用简单的回报会“更复杂”:
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
});
答案 0 :(得分:1)
您可以在StreamController周围使用包装器,如:
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;
}
}
然后调用这样的行为:
final controllerWrapper = new StreamControllerWrapper(new StreamController());
controllerWrapper.add(new A())
.then((result){
print(result);
});