Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop listening to event from inside event listener

Tags:

events

dart

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?

like image 495
dhasenan Avatar asked Dec 15 '13 06:12

dhasenan


People also ask

How do you stop an event listener?

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.

Should you always remove event listeners?

TLDR; Always remove event listeners when you don't plan on using them any longer.

How do you make Eventlistener work only once?

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.

Can event listeners be nested?

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.


1 Answers

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.

like image 136
dhasenan Avatar answered Sep 23 '22 20:09

dhasenan