DEV Community

Cover image for Passing objects between Activities using RxAndroid
Rishabh Tatiraju
Rishabh Tatiraju

Posted on

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 (among many other ways) to transfer objects between two Activities, and it’s pretty damn simple (well, of sorts!)

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!

Note: 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>()
    }
}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)