An Event Bus using Dart Streams for decoupling applications

Last update: May 11, 2022

Event Bus

A simple Event Bus using Dart Streams for decoupling applications.

Star this Repo Pub Package

GitHub | Pub | Demos and Examples

Event Bus Pattern

An Event Bus follows the publish/subscribe pattern. It allows listeners to subscribe for events and publishers to fire events. This enables objects to interact without requiring to explicitly define listeners and keeping track of them.

Event Bus and MVC

The Event Bus pattern is especially helpful for decoupling MVC (or MVP) applications.

One group of MVC is not a problem.

Model-View-Controller

But as soon as there are multiple groups of MVCs, those groups will have to talk to each other. This creates a tight coupling between the controllers.

Multi Model-View-Controllers

By communication through an Event Bus, the coupling is reduced.

Event Bus

Usage

1. Create an Event Bus

Create an instance of EventBus and make it available to other classes.

Usually there is just one Event Bus per application, but more than one may be set up to group a specific set of events.

import 'package:event_bus/event_bus.dart';

EventBus eventBus = EventBus();

Note: The default constructor will create an asynchronous event bus. To create a synchronous bus you must provide the optional sync: true attribute.

2. Define Events

Any Dart class can be used as an event.

class UserLoggedInEvent {
  User user;

  UserLoggedInEvent(this.user);
}

class NewOrderEvent {
  Order order;

  NewOrderEvent(this.order);
}

3. Register Listeners

Register listeners for specific events:

eventBus.on<UserLoggedInEvent>().listen((event) {
  // All events are of type UserLoggedInEvent (or subtypes of it).
  print(event.user);
});

Register listeners for all events:

eventBus.on().listen((event) {
  // Print the runtime type. Such a set up could be used for logging.
  print(event.runtimeType);
});

About Dart Streams

EventBus uses Dart Streams as its underlying mechanism to keep track of listeners. You may use all functionality available by the Stream API. One example is the use of StreamSubscriptions to later unsubscribe from the events.

StreamSubscription loginSubscription = eventBus.on<UserLoggedInEvent>().listen((event) {
  print(event.user);
});

loginSubscription.cancel();

4. Fire Events

Finally, we need to fire an event.

User myUser = User('Mickey');
eventBus.fire(UserLoggedInEvent(myUser));

Using Custom Stream Controllers

Instead of using the default StreamController you can use the following constructor to provide your own.

An example would be to use an RxDart Subject as the controller.

import 'package:rxdart/rxdart.dart';

EventBus behaviorBus = EventBus.customController(BehaviorSubject());

Running / Building / Testing

  • Run from the terminal: webdev serve
  • Build from the terminal: webdev build
  • Testing: pub run build_runner test -- -p chrome

License

The MIT License (MIT)

GitHub

https://github.com/marcojakob/dart-event-bus
Comments
  • 1. Flutter: listening callback not be called

    In my "HomePage" initState function, I place the following code for listening to NewOrderEvent:

    import '../eventbus/eventbus.dart';
    .....
    @override
    void initState() {
      super.initState();
      eventBus.on<NewOrderEvent>().listen((event) {
        print("event fired: $event");
      });
    }
    

    These code works fine and in main.dart file, I invoke eventBus.fire(new NewOrderEvent("some data"); when my app receive message from Firebase Cloud Message, the eventBus.fire function is indeed be invoked, but the listen callback function not be called.

    This is my "eventbus.dart" file content:

    import 'package:event_bus/event_bus.dart';
    
    EventBus eventBus = new EventBus();
    
    class NewOrderEvent {
      Map order;
    
      NewOrderEvent(this.order);
    }
    

    I print the firing eventBus object and listening eventBus object: screenshot 2018-12-09 17 47 57

    They are indeed the same object.

    BTW, the following are property and methods of the eventBus object: screenshot 2018-12-09 17 53 36

    Reviewed by Julyyq at 2018-12-09 09:55
  • 2. Not Firing from second page

    main page

           @override
      void initState() {
    	_listen();
      }
    
      var result;
      void _listen(){
    	eventBus.on<UserLoggedInEvent>().listen((event){
    	  log('eventevent'+ event.text);
    	});
      }
    

    and Second poge

            onTap: () => {
                          eventBus.fire(new UserLoggedInEvent('vvvvvvvvvvvv'))
           }
    
    Reviewed by Naguchennai at 2020-06-16 09:38
  • 3. Receive Event two times

    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.

    Reviewed by sumitb247software at 2019-11-05 11:41
  • 4. Can not set type on listen

    i have code like this:

    class AccountPhotoChangeEvent {
      final File file;
      AccountPhotoChangeEvent(this.file);
    }
    

    if i try register event like this:

    events.on(AccountPhotoChangeEvent).listen((AccountPhotoChangeEvent event) {
          
    });
    

    and error The argument type '(AccountPhotoChangeEvent) → Null' can't be assigned to the parameter type '(dynamic) → void'.

    Reviewed by lyquocnam at 2018-07-06 08:19
  • 5. Because event_bus uses mirrors it's less usable for client side

    This is a simple but very useful event bus implementation but the use of mirrors is very inconvenient for client side use. Would be great to have the old implementation back (and maintained) maybe as an alternative in it's separate library.

    I heard complaining others about this and just want to make you aware of the problem. In my projects, I currently use a fork anyway and am not affected currently.

    Reviewed by zoechi at 2015-05-03 15:22
  • 6. Does not work on windows

    [√] Flutter (Channel dev, 1.24.0-10.2.pre, on Microsoft Windows [Version 10.0.18363.1256], locale zh-CN) [X] Android toolchain - develop for Android devices X Unable to locate Android SDK. Install Android Studio from: https://developer.android.com/studio/index.html On first launch it will assist you in installing the Android SDK components. (or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions). If the Android SDK has been installed to a custom location, please use flutter config --android-sdk to update to that location.

    [√] Chrome - develop for the web [√] Visual Studio - develop for Windows (Visual Studio Community 2019 16.7.3) [!] Android Studio (not installed) [√] VS Code (version 1.52.1) [√] Connected device (3 available)

    ! Doctor found issues in 2 categories.

    Flutter channels: master

    • dev stable
    Reviewed by len8657 at 2021-01-20 08:09
  • 7. Getting an error that widget is not mounted

    setState() called after dispose(): MapState#dce2f(lifecycle state: defunct, not mounted) E/flutter (14865): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback. The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree. E/flutter (14865): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().

    Reviewed by michael-k-taylor at 2019-03-05 10:46
  • 8. Flutter

    This pattern looks good for flutter. I know bloc pattern is the recommended way with flutter but I have to do code reuse and so event bus is a better fit for my use case.

    Has anyone tried this ?

    Reviewed by ghost at 2018-09-07 11:24
  • 9. Add logging of events that flow through event bus.

    Its not a bug but rather a feature request: Event bus makes it harder to debug program. Having ability to switch logging on would greatly simplify life. It would be really nice to see events in the log as they are fired and consumed.

    Reviewed by Unisay at 2013-09-16 18:24
  • 10. In the example: pause and resume works on the event rather than the subscription.

    When testing the example app, i noticed that whenever you hit pause on one of the subscriptions, the OTHER subscriber fails to receive the event as well. Canceling a subscription works as expected, but pause and resume seems to target the whole event rather than just the subscription.

    Reviewed by snolde at 2013-05-18 00:56
  • 11. event from callback of top level function

    now i'm using foreground service with call back top level function .. and using a singleton class for both BackgroundTaskManger and EventBusManger when i receive an event from TaskManger can debugPrint a data but when i use EventBus fire cannot getting the event in any part of my code with on.listen .

    • are any solution with same this package or need another way to use send data in isolate ?
    Reviewed by nagyhero at 2021-12-12 01:53
  • 12. Holding events

    I'm having issues when firing an event before the listener is set, for this case the listener never gets the event. Are there any mechanism to hold the event until the listener is ready?

    Reviewed by jrojas25 at 2021-12-02 20:32

Related

An app to show everything bus related in Singapore, including arrival times and a directory
An app to show everything bus related in Singapore, including arrival times and a directory

NextBus SG An app to show everything bus related in Singapore, including bus arrival times and a directory, with extra features. ?? Gallery Click here

May 12, 2022
Bus Seat Booking App For Flutter
Bus Seat Booking App For Flutter

shani_bus(Bus Seat Booking App) splash screen Login page 3)Home screen Seat book

Apr 14, 2022
GeoLocationStreamsExample - Example of using streams with GeoLocator Package

geo_loc_stream A simple Flutter project I used to practice using Streams. Gettin

Apr 12, 2022
Small application where I worked with streams, firebase database, sorting, adding, modifying and deleting data.

messenger_app Small application where I worked with streams, firebase database, sorting, adding, modifying and deleting data. Features Provider: takin

Dec 19, 2021
Multi-Camera-Dashboard - Flutter App to View RTSP Streams
Multi-Camera-Dashboard - Flutter App to View RTSP Streams

9.9.2021 update I have updated the firebase db to be read only due to abuse. The save operation works if you import your own firebase and modify proje

May 16, 2022
Sangre - Sangre streams your backend queries in realtime to your clients minimizing the load via diffs

Sangre Sangre streams your backend queries in realtime to your clients minimizin

May 10, 2022
A flutter plugin exposing streams to android and iOS enviroment sensors (temp, light, pressure, humidty)
A flutter plugin exposing streams to android and iOS enviroment sensors (temp, light, pressure, humidty)

enviro_sensors A plugin that enables calling native device enviroment sensors. Readings are sent over an EventChannel and can be accessed with a liste

Feb 10, 2021
Return a Stream that emits null and done event when didChangeDependencies is called for the first time.
Return a Stream that emits null and done event when didChangeDependencies is called for the first time.

did_change_dependencies Author: Petrus Nguyễn Thái Học Return a Stream that emits null and done event when State.didChangeDependencies is called for t

Dec 1, 2021
A Flutter App That Find Party Event
A Flutter App That Find Party Event

EventZ ?? ?? Description: Discover events & upcoming events in your city and near you. Get personalized event recommendations! Find events your friend

Dec 21, 2021
Custom_Empty widget is flutter plugin which is designed to notify user about some event.
Custom_Empty widget is flutter plugin which is designed to notify user about some event.

Empty Widget Custom_Empty widget is flutter custom widget which is designed to notify user about some event. Screenshots Screenshots Screenshots Scree

Apr 4, 2022
OneAppFlutter - An official event app for HackRU
OneAppFlutter - An official event app for HackRU

One App Flutter The Official HackRU Flutter App Feel free to show some ❤️ and ⭐ the repo to support the project. Description What is the purpose of th

Apr 4, 2022
Flutter Event app UI design from Dribbble
Flutter Event app UI design from Dribbble

Flutter Event App Flutter event app UI design inspire from Dribble. Design Design from Dribble App UI UI GIF Screen HomePage Detail Implemented Featur

May 6, 2022
At its core, Mah-Event lets end-users initiate and find events corresponding to their interests and location
At its core, Mah-Event lets end-users initiate and find events corresponding to their interests and location

Mah-Event Application At its core, Mah-Event lets end-users initiate and find events corresponding to their interests and location. It allows people t

Mar 14, 2022
⚒️ A monorepo containing a collection of packages that provide useful functionality for building CLI applications in Dart.
⚒️ A monorepo containing a collection of packages that provide useful functionality for building CLI applications in Dart.

⚒️ Dart CLI Utilities A monorepo containing a collection of packages that provide useful functionality for building CLI applications in Dart. Document

May 1, 2022
Jan 11, 2022
This is a command-line app written on dart language for flutter applications that will help you to generate some boilerplate code

dart-generator Manual installation: 1- generate a platform executable from code dart compile exe main.dart -o generator this will generate a new gene

May 10, 2022
👉 A light-weight Emoji 📦 for Flutter and Dart-based applications with all up-to-date emojis 😄. Made from 💯% ☕ with ❤️!

flutter_emoji ?? A light-weight Emoji ?? for Flutter and Dart-based applications with all up-to-date emojis ?? . Made from ?? % ☕ with ❤️ ! Inspired f

May 2, 2022
A CLI to help with using FlutterFire in your Flutter applications.
A CLI to help with using FlutterFire in your Flutter applications.

FlutterFire CLI Documentation • License A CLI to help with using FlutterFire in your Flutter applications. Local development setup To setup and use th

May 17, 2022