7
import 'dart:async';

void main() {
  var dog = Dog();
  showTheDogACat(dog);
  print('outside');
  dog.bark();
}

class Cat{
  void runAway(msg){
    print("$msg I'm running away!");
  }
}

class Dog{  
  var _barkController = StreamController();
  Stream get onBark => _barkController.stream.asBroadcastStream();
  void bark(){
    _barkController.add("woof");
  }
}

showTheDogACat(dog){
  var cat = Cat();
  dog.onBark.listen((event)=>cat.runAway(event));
  dog.onBark.listen((event)=>print(event));       //why Exception: Stream already has subscriber?
  print('inside');
  dog.bark();
}

why does the 2nd dog.onBark.listen call generate Exception: stream already has subscriber? I thought broadcast streams could have many subscribers?

4

1 回答 1

12

getter在. onBark_ 新创建的广播流将尝试绑定到,但会失败,因为已经有一个监听器。asBroadcastStream_barkController.stream_barkController.stream

所以是的:广播流可能有多个侦听器,但asBroadcastStream不能在单个订阅流上多次调用该方法。

一种解决方案是缓存第一个asBroadcastStream.

于 2013-05-10T21:32:04.647 回答