marcojakob / dart-event-bus

An Event Bus using Dart Streams for decoupling applications
MIT License
755 stars 82 forks source link

Receive Event two times #29

Closed sumitb247software closed 4 years ago

sumitb247software commented 4 years ago

Hi @marcojakob I'm using event_bus: ^1.1.0 in flutter.

From one page i'm fire event like eventBus.fire(CustomEvents.START_MEDIA_SYNC_EVENT); and i'm listening event like

void getObserverData() { eventBus.on().listen((event) => {print(event.toString())}); } getObserverData() method is called from second screen build method.

I got the events two times. I initialize bus like this EventBus eventBus = new EventBus(); in one dart file.

Can please help me?

Thanks with best regards, Sumit Bhondave.

marcojakob commented 4 years ago

Your getObserverData() method is a strange thing. It doesn't return anything but installs a listener. So, if you call it two times, the listener is installed two times and you will receive the events two times.

sumitb247software commented 4 years ago

HI @marcojakob Thank you for your response. But where to install listener once in flutter.

Can please help me?

Thanks with best regards, Sumit Bhondave.

marcojakob commented 4 years ago

Just include this line somewhere in the program and don't call it multiple times (except if you want to listen to it in multiple components):

eventBus.on().listen((event) => {print(event.toString())});
sumitb247software commented 4 years ago

HI @marcojakob Issue is resolved. I install listener in initState(). Thank you.

Thanks with best regards, Sumit Bhondave.

xhidnoda commented 4 years ago

i think install the eventBus.on on initState() cause problem... in my case i put in the initState() and when push to another pageFlutter the initState() is calling again my eventBus.on. So i receive event two times. :( where is the correct way to put the listener of eventBus.on?

marcojakob commented 4 years ago

@xhidnoda I don't have experience with Flutter. But I know there is a dispose() function. If you register something in initState() you should probably cancel the subscription to the event bus in dispose().

xhidnoda commented 4 years ago

Ok i declare this:

StreamSubscription busEventListener;

Add listener like this in initState() :

busEventListener = eventBus.on<ClassEventResp>().listen((event) {
      _parseResponse(event.message);
    });

In dispone():

doctorEventListener.cancel();

But is not working..what is wrong? please help!

marcojakob commented 4 years ago

Sorry @xhidnoda. I can't provide much support here. But you should try debugging your application (or use logging) to see how many times you are registering for the same event.

xhidnoda commented 4 years ago

Sorry error of my code. I calledinitState()from my ListView many times. So I put the code logic outside the ListView, and it works perfect.

devmanzur commented 3 years ago

call eventBus.destroy(); on your dispose method