Stop listening to event from inside event listener Stop listening to event from inside event listener dart dart

Stop listening to event from inside event listener


Just declare the subscription before subscribing to the stream:

var subscription;subscription = stream.listen((event) {  if (f(event)) {    doStuff();    subscription.cancel();  } else {    doOtherStuff();  }});


Divide and conquer.

First, let's consider the if (f(event)) part. That takes only the first item that matches the predicate and performs an operation. There are two ways of doing this:

stream.where((event) => f(event)).take(1).listen((event) => doStuff());

That's the generic way of doing things, and it means we use the Stream interface all through. Another way of doing it, which might avoid a few addition and comparison operations, requires switching to the Future interface:

stream.firstWhere((event) => f(event)).then((event) => doStuff());

That only handles the first part of the condition. What about the second part? We want to grab everything until the condition holds true, so we'll use takeWhile:

stream.takeWhile((event) => !f(event)).listen((event) => doOtherStuff());

And Bob's your uncle.

If the code is essentially the same for both listeners, you can separate it out into another function, of course.