How to pass a callback function to a StreamControl

2019-08-03 08:16发布

问题:

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;
}