Passing objects between Activities using RxAndroid

Passing objects between Activities using RxAndroid

Want to pass data easily between activities? Tired of making classes Parcelable, or reluctant to make them Serializable? Good news — there is a way to transfer objects between two Activities using RxAndroid, and its quite easy!

This article assumes you to have implemented RxAndroid in your project. If you are new to ReactiveX for Android, here is an article that will help you to understand it better and help you set you up! All code snippets are in Kotlin language.

Creating a communication medium

In order to communicate between two Activities, we first create a Bus class with a static BehaviorSubject object that can be accessed from anywhere.

class AndroidBus { companion object { val behaviorSubject = BehaviorSubject.create<Any>() } }
Code language: Kotlin (kotlin)

Sending data from the source activity

From the source activity, you can get the BehaviorSubject object and push your data model into the bus as follows:

val myAwesomeDataModel = AwesomeDataModel() AndroidBus.behaviorSubject.onNext(myAwesomeDataModel)
Code language: Kotlin (kotlin)

Receiving data at the destination activity

In the destination activity, simply subscribe to the BehaviorSubject and retrieve the object. Just to be safe, make sure the object is of the same type that you’re expecting.

var myAwesomeDataModel: AwesomeDataModel? = null AndroidBus.behaviorSubject.subscribe { if (it is AwesomeDataModel) { myAwesomeDataModel = it } } if (myAwesomeDataModel != null) { // do stuff with your data model }
Code language: Kotlin (kotlin)

And that’s all! No Parcelable implementations, no making classes Serializable and losing performance, no Intents, no bundle keys, nothing! Isn’t RxAndroid wonderful?

What about sending multiple objects?

You can always add multiple objects into a HashMap, pass it using the above method and use the keys of individual objects to retrieve them back.

Tagged with: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*

eighteen + 1 =