0

我正在使用该dart:async库进行一些数据处理。我正在向 a 添加对象,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
});
4

1 回答 1

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);
  });
于 2013-06-27T17:39:46.163 回答