Publisher subscriber design pattern is extensively used in android to communicate between two blocks of code. Here we send data from one block of code to another block of code by keeping them decoupled and preserving the abstraction.
By using shared-flow
provide by kotlin and coroutines we implement this pattern and can use it in android without needing to use an additional library like event-bus
, rx-java
and deprecated API like local-boadcast-recievers
`
Demo
Design Pattern
The design pattern used here is called the publish-subscribe pattern. The subscriber just wait for any publishers to send them the data and when the publishers send the data they react to them
Earlier implementations used in Android
- Local-Broadcast Reciever: Implemented using the broadcast receiver which is currently deprecated.
- Event-Bus: Third part solution provided by the green-robot provider which provides a library that has this solution implemented.
- Rx-Bus: This solution is implemented using Rx-Java.
Using Shared-Flow
With the introduction of kotlin and flow API, We can design an implementation of publisher and subscriber pattern and use them to communicate from one coroutine at one part of the code to another coroutine in another part of the code without using any additional third-party libraries that provide this solution