TopicEventBus is Easy to use, type safe way of implementing Publish–subscribe design pattern.

Related tags

Event TopicEventBus
Overview

TopicEventBus

Publish–subscribe design pattern implementation framework, with ability to publish events by topic. (NotificationCenter extended alternative)

On Medium: https://medium.com/@matancohen_22770/why-you-should-stop-using-notificationcenter-and-start-using-topiceventbus-c4c7ab312643

Language

TopicEventBus Icon

About:

TopicEventBus is Easy to use, type safe way of implementing Publish–subscribe design pattern.

There are many other libraries out there, aiming to solve this issue, but none of them support publishing events by topic, in a type-safe way, with no magic strings.

Also, TopicEventBus holds weak referenced for Its observers, so you don't have to be afraid of memory leaks.

What is a topic?

The topic is for example, when you would like to publish "ConversationUpdateEvent" yet have the ability to publish that event only to listeners with conversation id "1234" or to all listeners.

Specifying the conversation Id is specifying a topic for that event.

Show me the code! and what's in it for me.

Let's build a chat app!

In this app, we are going to have multiple conversations screens, each one of them would like to know only about changes to Its conversation.

The first step, create an event for conversation update:

class ConversationChangedEvent: TopicEvent {
    let newTitle: String
    init(conversationId: String, newTitle: String) {
        self.newTitle = newTitle
        super.init()
        self.key = conversationId
    }
}

Every event must inherit from "TopicEvent," and in case it has a topic (Our example it will be the conversation id) set "key" property to the correct value.

Now inside ConversationVC, subscribe to this event:

Notice you only need to specify the return value you are expecting, for TopicEventBus to figure out the event you are subscribing for

class ConversationVC: UIViewController {
    let topicEventBus: TopicEventBus
    let conversationId = "1234"
    
    init(topicEventBus: TopicEventBus) {
        self.topicEventBus = topicEventBus
    }
   
    override func viewDidLoad() {
        super.viewDidLoad()
        _ = self.topicEventBus.subscribe(topic: conversationId, callback: { (conversationChangedEvent: ConversationChangedEvent) in
            // This will run every time "ConversationChangedEvent" with id 1234 will be fired.
        })
    }
}

This is how you fire an event:

class FiringService {
    let topicEventBus: TopicEventBus
    init(topicEventBus: TopicEventBus) {
        self.topicEventBus = topicEventBus
    }
    
    func conversationTitleChanged() {
        self.topicEventBus.fire(event: ConversationChangedEvent.init(conversationId: "1234",
                                                                                            newTitle: "First update"))
    }
}

You did it! You fired your first event with topic 🤗 🎉

API

If you subscribe to event and specify no topic, you will receive all events from that type, no matter their key:

_ = self.topicEventBus.subscribe { (conversationChangedEvent: ConversationChangedEvent) in
  // All events from this type: ConversationChangedEvent will trigger this block
}

Unsubscribe by calling "stop" on the returned object after subscribing:

let listener = self.topicEventBus.subscribe(topic: conversationId, callback: { (conversationChangedEvent: ConversationChangedEvent) in
//
})
listener.stop()        

On app log out, terminate TopicEventBus by just calling:

self.topicEventBus.terminate()

Example project

Please notice example project contains tests to support all edge cases, plus example code from the above snippets.

Installation

Cocoapods

TopicEventBus is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'TopicEventBus'

Manually

  1. Download and drop /TopicEventBus folder in your project.
  2. Congratulations!

Author

Matan made this with ❤️ .

You might also like...
A publish/subscribe EventBus optimized for iOS

SwiftEventBus Allows publish-subscribe-style communication between components without requiring the components to explicitly be aware of each other Fe

FluxCapacitor makes implementing Flux design pattern easily with protocols and typealias.
FluxCapacitor makes implementing Flux design pattern easily with protocols and typealias.

FluxCapacitor makes implementing Flux design pattern easily with protocols and typealias. Storable protocol Actionable protocol Dispatch

Good-news - A simple news application built implementing the MVVM design pattern.  It is integrated with a news api which returns JSON
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

🚀Comprehensive Redux library for SwiftUI, ensures State consistency across Stores with type-safe pub/sub pattern.
🚀Comprehensive Redux library for SwiftUI, ensures State consistency across Stores with type-safe pub/sub pattern.

🚀Comprehensive Redux library for SwiftUI, ensures State consistency across Stores with type-safe pub/sub pattern.

Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend
Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend

Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend. Using Argo

Easy to use UITableViewCell implementing swiping to trigger actions.
Easy to use UITableViewCell implementing swiping to trigger actions.

SwipyCell Swipeable UITableViewCell inspired by the popular Mailbox App, implemented in Swift. Preview Exit Mode The .exit mode is the original behavi

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

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,

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 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 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-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer documentation.

Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer docum

📬 A lightweight implementation of an observable sequence that you can subscribe to.
📬 A lightweight implementation of an observable sequence that you can subscribe to.

Features Lightweight Observable is a simple implementation of an observable sequence that you can subscribe to. The framework is designed to be minima

📬 A lightweight implementation of an observable sequence that you can subscribe to.
📬 A lightweight implementation of an observable sequence that you can subscribe to.

Features Lightweight Observable is a simple implementation of an observable sequence that you can subscribe to. The framework is designed to be minima

🌳 Environment – a nicer, type-safe way of working with environment variables in Swift.

🌳 Environment Welcome to Environment – a nicer, type-safe way of working with environment variables in Swift. Usage Access Environment Variables The

📄 A Swift DSL for writing type-safe HTML/CSS in SwiftUI way

📄 swift-web-page (swep) Swep is a Swift DSL for writing type-safe HTML/CSS in SwiftUI way. Table of Contents Motivation Examples Safety Design FAQ In

A Swift mixin for reusing views easily and in a type-safe way (UITableViewCells, UICollectionViewCells, custom UIViews, ViewControllers, Storyboards…)
A Swift mixin for reusing views easily and in a type-safe way (UITableViewCells, UICollectionViewCells, custom UIViews, ViewControllers, Storyboards…)

Reusable A Swift mixin to use UITableViewCells, UICollectionViewCells and UIViewControllers in a type-safe way, without the need to manipulate their S

Owner
Matan Abravanel
Software Engineer At Platterz http://stackoverflow.com/users/3238178/mcmatan http://www.matanabrava.com
Matan Abravanel
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

Postmates Inc. 708 Jun 29, 2022
📬 A lightweight implementation of an observable sequence that you can subscribe to.

Features Lightweight Observable is a simple implementation of an observable sequence that you can subscribe to. The framework is designed to be minima

Felix M. 133 Aug 17, 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
NoticeObserveKit is type-safe NotificationCenter wrapper.

NoticeObserveKit NoticeObserveKit is type-safe NotificationCenter wrapper. // .keyboardWillShow is a static property. Notice.Center.default.observe(na

Taiki Suzuki 147 Nov 24, 2022
RxReduce is a lightweight framework that ease the implementation of a state container pattern in a Reactive Programming compliant way.

About Architecture concerns RxReduce Installation The key principles How to use RxReduce Tools and dependencies Travis CI Frameworks Platform Licence

RxSwift Community 125 Jan 29, 2022
Observable is the easiest way to observe values in Swift.

Observable is the easiest way to observe values in Swift. How to Create an Observable and MutableObservable Using MutableObservable you can create and

Robert-Hein Hooijmans 368 Nov 9, 2022
Easy Swift Futures & Promises.

❗️ Archived now ❗️ Since Apple released Combine framework, I decide to archive this repo. You still can use this repo as an example of Future/Promise

Dmytro Mishchenko 40 Sep 23, 2022
Publish–subscribe design pattern implementation framework, with an ability to publish events by topic.

TopicEventBus Publish–subscribe design pattern implementation framework, with ability to publish events by topic. (NotificationCenter extended alterna

Matan Abravanel 55 Nov 29, 2021
Publish–subscribe design pattern implementation framework, with an ability to publish events by topic.

TopicEventBus Publish–subscribe design pattern implementation framework, with ability to publish events by topic. (NotificationCenter extended alterna

Matan Abravanel 55 Nov 29, 2021
SwiftEventBus - A publish/subscribe EventBus optimized for iOS

Allows publish-subscribe-style communication between components without requiring the components to explicitly be aware of each other

César Ferreira 1k Jan 6, 2023