How to pass a callback function to a StreamController

被刻印的时光 ゝ 提交于 2019-12-11 05:02:06

问题


I was wondering something I'm creating a StreamController like that:

class {
  StreamController _controller = 
      new StreamController(onListen: _onListen(), onPause: _onPause(), 
          onResume: _onResume(), onCancel: _onCancel());

    Stream get stream => _controller.stream;
}

in an other class I invoke

var sub = myInstance.stream.listen(null);

and I'm really surprise that all the callbacks in the StreamController's constructor are triggered.

Is there an explanation for this behavior ?

Cheers !


回答1:


You should not add the parens ()

class {
  StreamController _controller = 
      new StreamController(onListen: _onListen, onPause: _onPause, 
          onResume: _onResume, onCancel: _onCancel);

    Stream get stream => _controller.stream;
}

This way the expression you pass as argument to onListen, onPause, ... is a reference to a method/function. When you add parents the expression is a method/function call and the actual argument to onListen, onPause, ... is the return value of the expression.

Alternatively you could to it this way (I omitted arguments because I want to save the time to looke them up)

class {
  StreamController _controller = 
      new StreamController(onListen: () => _onListen(), onPause: () => _onPause(), 
          onResume: () => _onResume(), onCancel: () => _onCancel());

    Stream get stream => _controller.stream;
}


来源:https://stackoverflow.com/questions/26892259/how-to-pass-a-callback-function-to-a-streamcontroller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!