DEV Community

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

Posted on

1 1

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.

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools 🔁

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay