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?
The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.
TLDR; Always remove event listeners when you don't plan on using them any longer.
Using the once option We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.
The final step, the callback function, can be written as a nested anonymous function inside the event listener or can be a designated function fully defined in a separate function. The callback handles the resulting work you want to happen after an event has occurred.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With