An Event Bus using Dart Streams for decoupling applications

Overview

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)

Comments
  • Flutter: listening callback not be called

    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

    opened by Julyyq 12
  • Not Firing from second page

    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'))
           }
    
    opened by Naguchennai 10
  • Receive Event two times

    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.

    opened by sumitb247software 10
  • Can not set type on listen

    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'.

    opened by lyquocnam 6
  • Because event_bus uses mirrors it's less usable for client side

    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.

    opened by zoechi 5
  • Holding events

    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?

    opened by jrojas25 3
  • Does not work on windows

    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
    opened by len8657 3
  • Getting an error that widget is not mounted

    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().

    opened by michael-k-taylor 3
  • Flutter

    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 ?

    opened by ghost 3
  • Add logging of events that flow through event bus.

    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.

    enhancement 
    opened by Unisay 3
  • In the example: pause and resume works on the event rather than the subscription.

    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.

    opened by snolde 3
Releases(v2.0.0)
  • v2.0.0(Mar 4, 2021)

  • v1.1.0(Mar 27, 2019)

  • v1.0.3(Feb 13, 2019)

  • v1.0.0(Jul 6, 2018)

    • Migrate to Dart 2.
    • BREAKING CHANGE: The on method now has a generic type. The type must be passed as a type argument instead of a method parameter. Change myEventBus.on(MyEventType) to myEventBus.on<MyEventType>().
    • BREAKING CHANGE: Every EventBus is now hierarchical so that listeners will also receive events of subtypes of the specified type. This is exactly the way that HierarchicalEventBus worked. So HierarchicalEventBus has been removed. Use the normal EventBus instead.
    Source code(tar.gz)
    Source code(zip)
  • v0.4.1(May 13, 2015)

  • v0.4.0(May 3, 2015)

    • BREAKING CHANGE: Moved the HierarchicalEventBus to a separate library to be able to remove dart:mirrors from the normal EventBus.
      Users of the hierarchical event bus must import event_bus_hierarchical.dart and replace the use of the factory constructor EventBus.hierarchical() with the HierarchicalEventBus constructor.
    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(Sep 8, 2014)

    • BREAKING CHANGE: Changed and simplified the EventBus API. We can now dispatch any Dart object as an event. Before, we had to create an EventType for every type of event we wanted to fire. Now we can use any class as an event. Listeners can (optionally) filter events by that class.
    • Added a way to create a hierarchical event bus that filters events by class and their subclasses. This currently only works with classes extending other classes and not with implementing an interface. We might have to wait for https://code.google.com/p/dart/issues/detail?id=20756 to enable interfaces.
    • BREAKING CHANGE: Default to async mode instead of sync. This now matches the of the Dart streams.
    • BREAKING CHANGE: Removed LoggingEventBus. Reason is that logging can easily be implemented with a event listener that listens for all events and logs them.
    Source code(tar.gz)
    Source code(zip)
  • v0.2.4(Nov 11, 2013)

  • v0.2.3(Sep 16, 2013)

  • v0.2.2(Sep 16, 2013)

  • v0.2.1(Jul 3, 2013)

  • v0.2.0(Jul 3, 2013)

    • Update to new Dart SDK v0.5.13.1_r23552.
    • Using Darts new Stream.broadcast() factory.
    • Provide option for synchronous broadcasting of events.
    • Update unit tests and example.
    • Create demo page.
    Source code(tar.gz)
    Source code(zip)
  • v0.1.3(Jul 3, 2013)

  • v0.1.2(Jul 3, 2013)

    • Change in README: contained wrong license (Apache instead of MIT).
    • Remove import 'package:meta/meta.dart' in event_bus.dart as it is not needed and may cause an error if used as pub package.
    Source code(tar.gz)
    Source code(zip)
Owner
Marco Jakob
Marco Jakob
An Event-based system, highly inspired by NodeJS's Event Emitter

An Event-based system, highly inspired by NodeJS's Event Emitter. This implementation uses generic types to allow for multiple data types, while still being intuitive.

JUST A SNIPER ツ 5 Dec 1, 2022
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

null 103 Sep 13, 2022
Bus Seat Booking App For Flutter

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

null 5 Oct 8, 2022
GeoLocationStreamsExample - Example of using streams with GeoLocator Package

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

CypherZox 3 Nov 24, 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

Danil Shubin 2 Dec 19, 2021
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

Mitch Ross 54 Jan 1, 2023
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

P.O.M 5 Nov 27, 2022
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

Barbadose 6 Feb 10, 2021
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

Petrus Nguyễn Thái Học 5 Nov 9, 2022
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

李瑞孟 4 Jun 30, 2022
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

Sonu Sharma 66 Nov 17, 2022
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

HackRU 24 Dec 10, 2022
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

Chunlee Thong 85 Dec 20, 2022
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

Palm Jumnongrat 4 Oct 23, 2022
Flutter Image add drag sort, Image add drag sort, support click event, delete, add, long press drag sort.

flutter_image_add_drag_sort Flutter Image add drag sort, Image add drag sort, support click event, delete, add, long press drag sort, support video fi

null 5 Jun 23, 2020
Flutter application for event manage API- Hiring challenge

Event Manage App Simple flutter application for listing and filtering out events. Setup guide Install Flutter Follow the official guide from the flutt

null 3 Oct 25, 2022
Flying Fish is full-stack Dart framework - a semi-opinionated framework for building applications exclusively using Dart and Flutter

Flying Fish is full-stack Dart framework - a semi-opinionated framework for building applications exclusively using Dart and Flutter.

Flutter Fish 3 Dec 27, 2022
⚒️ 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

Invertase 14 Oct 17, 2022