gpt4 book ai didi

dart - Dart Streams取消订阅

转载 作者:行者123 更新时间:2023-12-03 02:53:48 25 4
gpt4 key购买 nike

你好!

我正在尝试了解Dart中流的工作原理。
这是一个简单的示例:

  • 我们有Publisher
    class Publisher {

    StreamController<String> _publishCtrl = new StreamController<String>();
    Stream<String> onPublish;

    Publisher() {
    onPublish = _publishCtrl.stream.asBroadcastStream();
    }

    void publish(String s) {
    _publishCtrl.add(s);
    }
    }
  • Reader
    class Reader {
    String name;
    Reader(this.name);
    read(String s) {
    print("My name is $name. I read string '$s'");
    }
    }
  • 和简单函数main():

    main() {
    Publisher publisher = new Publisher();

    Reader john = new Reader('John');
    Reader smith = new Reader('Smith');

    publisher.onPublish.listen(john.read);
    publisher.onPublish.listen(smith.read);

    for (var i = 0; i < 5; i++) {
    publisher.publish("Test message $i");
    }
    }

  • 作为代码的结果,我从阅读器 John获得5条控制台消息,并从阅读器 Smith获得5条消息。

    My name is John. I read string 'Test message 0'
    My name is Smith. I read string 'Test message 0'
    My name is John. I read string 'Test message 1'
    My name is Smith. I read string 'Test message 1'
    My name is John. I read string 'Test message 2'
    My name is Smith. I read string 'Test message 2'
    My name is John. I read string 'Test message 3'
    My name is Smith. I read string 'Test message 3'
    My name is John. I read string 'Test message 4'
    My name is Smith. I read string 'Test message 4'

    一切正常。但是,如果我尝试更改 for周期,以便经过2步阅读器 Smith stoppes接收到该消息,则该消息将仅接收阅读器 John
    这是更改函数 main ()的示例:

        main() {
    Publisher publisher = new Publisher();

    Reader john = new Reader('John');
    Reader smith = new Reader('Smith');

    publisher.onPublish.listen(john.read);
    var smithSub = publisher.onPublish.listen(smith.read);

    for (var i = 0; i < 5; i++) {
    publisher.publish("Test message $i");

    if (i > 2) {
    smithSub.cancel();
    }
    }
    }

    如果运行此代码,则控制台将仅由 John 发布:

    My name is John. I read string 'Test message 0'
    My name is John. I read string 'Test message 1'
    My name is John. I read string 'Test message 2'
    My name is John. I read string 'Test message 3'
    My name is John. I read string 'Test message 4'

    但我认为读者应该有3条消息 Smith

    请告诉我我所知道的对吗?如果没有,请帮助我,以了解发生这种情况的原因。

    非常感谢你。

    最佳答案

    要么创建一个同步StreamController

    StreamController<String> _publishCtrl = new StreamController<String>(sync: true);

    或允许 Controller 在发送新商品之前处理这些商品

      int i = 0;
    Future.doWhile(() {
    i++;

    publisher.publish("Test message $i");

    if (i > 2) {
    subscriptions
    ..forEach((s) => s.cancel())
    ..clear();
    }
    return i < 5;
    }

    关于dart - Dart Streams取消订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27622213/

    25 4 0