🚎 Simple type-safe event bus implementation in swift

Overview

🚎 RealEventsBus

RealEventsBus is a small swift experiment package to implement a basic type-safe event bus mechanism.
Some other implementations in GitHub are the sources of inspiration for this package.

You can use it as replacement for standard NSNotification's one-to-many messaging. It uses GCD for messagings, it's thread-safe and, best of all, it's type safe.

⭐️ Feature Highlights

  • It's type safe
  • Implement custom messages; just set conformance to Event or BufferedEvent type
  • Messages/observers are posted and registered in thread safe
  • Easy to use; just one line to register and post events
  • Supports for buffered events (get the last value published by a bus)

πŸ•΅οΈ How It Works

This example uses enum as datatype for event.
Btw you can use any type you want as event, struct or class (see the other example below). First of all we need to define a custom event; if your event is a group of different messages this is the best thing you can do:

public enum UserEvents: Event {
    case userDidLogged(username: String)
    case userLoggedOut
    case profileUpdated(fullName: String, age: Int)
}

Suppose you want to be notified about this kind of events in your UIViewController:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        Bus<UserEvents>.register(self) { event in
            switch event {
            case .profileUpdated(let fullName, let age):
                print("Profile updated with '\(fullName)', which is \(age) old")
            case .userDidLogged(let username):
                print("User '\(username)' logged in")
            case .userLoggedOut:
                print("User logged out")
            }
        }
    }

    deinit {
        // While it's not required (it does not generate any leak) 
        // you may want to unregister an observer when it's not needed anymore.
        Bus<UserEvents>.unregister(self)
    }
}

When you need to post new events to any registered obserer like the one above just use post function:

Bus<UserEvents>.post(.userDidLogged(username: "danielemm"))

BufferedEvent

If your event is conform to BufferedEvent instead of Event you can use the lastValue() function to get the latest posted value into the bus. It's like Rx.
Moreover: when a new observer is registered it will receive the last value posted into the bus, if any.

This is an example.

First of all we define the message:

public class CustomEvent: BufferedEvent {
    
    var messageValue: String
    var options: [String: Any?]?
    
    public init(value: String, options: [String: Any?]) {
        self.messageValue = value
        self.options = options
    }

}
    // Post a new event
    Bus<CustomEvent>.post(.init(value: "Some message", options: ["a": 1, "b": "some"]))

    // At certain point in your code:
    let lastValue = Bus<CustomEvent>.lastValue() // print the type above!

Custom Dispatch Queue

You can also specify a queue where the message callback will be called.
By default the .main queue is used.

Bus<CustomEvent>.register(self, queue: .global()) { _ in // in background queue
   // do something
}        

Install

Swift Package Manager

To install it using the Swift Package Manager specify it as dependency in the Package.swift file:

dependencies: [
    .package(url: "https://github.com/malcommac/RealEventsBus.git", branch: "main"),
],

CocoaPods

Not yet supported.

Author

This little experiment was created by Daniele Margutti.
If you like it you can fork or open a PR or report an issue.
If you want to support my work just take a look at my Github Profile.

License

It's the MIT license.

You might also like...
Modern thread-safe and type-safe key-value observing for Swift and Objective-C

Now Archived and Forked PMKVObserver will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork o

A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety
A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety

A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety. Type Safe No more userInfo dictionary and Downcasting,

Contains the swift rewrite of Find My Bus NJ iOS App
Contains the swift rewrite of Find My Bus NJ iOS App

FIND MY BUS NJ 2 An app for tracking NJ Transit bus times. Dependancies Alamofire SwiftyJSON PKHUD Fabric Getting started Install fastlane and imagema

Type-safe CAAnimation wrapper. It makes preventing to set wrong type values.
Type-safe CAAnimation wrapper. It makes preventing to set wrong type values.

TheAnimation TheAnimation is Type-safe CAAnimation wrapper. Introduction For example, if you want to animate backgroundColor with CABasicAnimation, yo

A lightweight and efficient bus tracker app for the Miami-Dade Transit System
A lightweight and efficient bus tracker app for the Miami-Dade Transit System

A lightweight bus tracker app for the Miami-Dade Transit System Built in Swift, this app features a favorites page, real-time bus location and ETA, us

A phantom type is a custom type that has one or more unused type parameters.

PhantomTypes A phantom type is a custom type that has one or more unused type parameters. Phantom types allow you to enforce type-safety without sacri

Swift implementation of KERI (Key Event Receipt Infrastructure)

keri-swift Swift implementation of KERI (Key Event Receipt Infrastructure) Introduction keri-swift is an open source go implementation of the Key Even

Simple Interface Core Animation. Run type-safe animation sequencially or parallelly
Simple Interface Core Animation. Run type-safe animation sequencially or parallelly

Simple Interface Core Animation Sica can execute various animations sequentially or parallelly. Features Animation with duration and delay parallel /

QueryKit, a simple type-safe Core Data query language.
QueryKit, a simple type-safe Core Data query language.

QueryKit QueryKit, a simple type-safe Core Data query language. Usage QuerySetPerson(context, "Person")

 SQLite.swift - A type-safe, Swift-language layer over SQLite3.
SQLite.swift - A type-safe, Swift-language layer over SQLite3.

SQLite.swift provides compile-time confidence in SQL statement syntax and intent.

Swift-multipart-formdata - MultipartFormData: Build multipart/form-data type-safe in Swift

MultipartFormData Build multipart/form-data type-safe in Swift. A result builder

Straightforward, type-safe argument parsing for Swift

Swift Argument Parser Usage Begin by declaring a type that defines the information that you need to collect from the command line. Decorate each store

Himotoki (紐解き) is a type-safe JSON decoding library written purely in Swift.

Himotoki Himotoki (紐解き) is a type-safe JSON decoding library written purely in Swift. This library is highly inspired by the popular Swift JSON parsin

πŸ•° Type-safe time calculations in Swift

Time This micro-library is made for you if: You have ever written something like this: let interval: TimeInterval = 10 * 60 To represent 10 minutes. U

A type-safe, high-level networking solution for Swift apps
A type-safe, high-level networking solution for Swift apps

What Type-safe network calls made easy Netswift offers an easy way to perform network calls in a structured and type-safe way. Why Networking in Swift

Protocol oriented, type safe, scalable design system foundation swift framework for iOS.
Protocol oriented, type safe, scalable design system foundation swift framework for iOS.

Doric: Design System Foundation Design System foundation written in Swift. Protocol oriented, type safe, scalable framework for iOS. Features Requirem

Type-Safe Associated Objects in Swift

Type-Safe Associated Objects in Swift TSAO is an implementation of type-safe associated objects in Swift. Objective-C associated objects are useful, b

Easy and type-safe iOS table and collection views in Swift.
Easy and type-safe iOS table and collection views in Swift.

Quick Start TL;DR? SimpleSource is a library that lets you populate and update table views and collection views with ease. It gives you fully typed cl

SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them type-safe to use.
SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them type-safe to use.

SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them type-safe to use.

Owner
Daniele Margutti
iOS & macOS Engineer, UI/UX Lover. Tech Lead at Immobiliare.it. Continuous improvement is better than delayed perfection.
Daniele Margutti
APNSUtil is makes code simple using apple push notification service

APNSUtil APNSUtil makes code simple settings and landing for apple push notification service. Features Using apple push notification service simply No

Steve Kim 30 Mar 24, 2022
A fully customizable library to easily display Animated Toast Messages in iOS using Swift!

CustomToastView-swift A fully customizable library to easily display Animated Toast Messages in iOS using Swift! Preview - All the custom toasts you c

Leticia Rodriguez 13 Aug 20, 2022
Easily create Local Notifications in swift - Wrapper of UserNotifications Framework

In IOS 10, apple updated their library for Notifications and separated Local and push notifications to a new framework: User Notifications This librar

Devesh Laungani 208 Dec 14, 2022
A Swift Library for Dynamic Island Push Notification.

Push Notification With Dynamic Island Handle Push Notification with Dynamic Island ?? Descreption: Since there is not library for Apple Push Notificat

Amir Diafi 5 Nov 12, 2022
A Swift event bus for UIWebView/WKWebView and JS.

An event bus for sending messages between UIWebView/WKWebView and embedded JS. Made with pure Swift. Features Easy, fast and reliable event bus system

Coshx 149 Oct 9, 2022
Type-safe networking abstraction layer that associates request type with response type.

APIKit APIKit is a type-safe networking abstraction layer that associates request type with response type. // SearchRepositoriesRequest conforms to Re

Yosuke Ishikawa 1.9k Dec 30, 2022
Type-safe event handling for Swift

emitter-kit v5.2.2 A replacement for NSNotificationCenter#addObserver and NSObject#addObserver that is type-safe and not verbose. import EmitterKit /

Alec Larson 570 Nov 25, 2022
An Event View based on Apple's Event Detail View. Written in Swift 3. Supports ARC, Autolayout and editing via StoryBoard.

An Event View based on Apple's Event Detail View. Written in Swift 3. Supports ARC, Autolayout and editing via StoryBoard. Installation CocoaPods PTEv

Aman Taneja 36 Oct 5, 2022
Event management iOS app for organizers using Open Event Platform

Open Event Organizer iOS App Event management app for organizers using Open Event Platform Roadmap Make the app functionality and UI/UX similar to the

FOSSASIA 1.5k Dec 29, 2022
MemoryCache - type-safe, thread-safe memory cache class in Swift

MemoryCache is a memory cache class in swift. The MemoryCache class incorporates LRU policies, which ensure that a cache doesn’t

Yusuke Morishita 74 Nov 24, 2022