How To Implement The Event Bus Pattern With Kotlin SharedFlow In Your Android App

Handle app wide events easily without unnecessary coupling

Yanneck Reiß
Tech Takeaways

--

Photo by Karol D from Pexels

The Event Bus design pattern is a well-known practice that has been widely used in many Android apps in the past to achieve an event-driven architecture.

With the slow replacement of Java by Kotlin over the recent years, this approach was almost forgotten. Kotlin itself and also other popular frameworks nowadays offer various options for implementing a publisher/subscriber architecture, such as Kotlin Flow, RxJava, or LiveData.

Because of that, the Event Bus approach has almost been forgotten, even if there were possibilities to reimplement this pattern. With a few trade-offs, you could achieve almost the same with Kotlin Broadcast Channels for example.

With the release of Kotlin 1.4 and the promotion of SharedFlows and StateFlows to their stable versions, a new and way easier way for implementing the EventBus design pattern approach appeared.

In this article, we take a look at the fundamentals of the pattern, discuss the difference between Observer- and Publish/Subscriber Pattern, and see how it can be implemented with SharedFlows.

--

--

Yanneck Reiß
Tech Takeaways

Follow me on my journey as a professional mobile and fullstack developer