Stop listening to event from inside event listener

Viewed 3626

I want to listen to an event stream, then conditionally stop listening based on the received event.

In short, I'd like to use:

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

This obviously doesn't work; subscription doesn't exist until the listener has been created, resulting in an error.

How do I do this?

2 Answers
Related