user098765
user098765

Reputation: 11

Passing large data between activities in Kotlin

I'm trying to pass large data from one activity to another. For business reasons, I cannot save this data to persistent storage and need it to stay in memory.

Up until now, I've been using Intents to pass Serializable data, but with larger data, I've been receiving TranstactionTooLarge exceptions/crashes.

What are my options? I am using Kotlin, so Kotlin-specific solutions are welcome.

I've thought of using Singletons, but I'm unsure of the side effects of that, or if there is a better solution.

Upvotes: 1

Views: 800

Answers (2)

Michal Harakal
Michal Harakal

Reputation: 1035

TransactionTooLargeexception reflects limitations of IPC mechanism on Android, in the way, how data are transfered between processes.

Since you are sharing data between activities, given restrictions you have, following possibilities came to my mind:

  1. keeping data in a singleton instance of repository (which takes reponsibility for reloading of data in case, they get lost during recreating of activities etc.) and trafering just unique indetifier(or identifiers)
  2. reduce size of data by simple data transformation or compression(integer instead of float, long for Date etc.)
  3. as pointed out by @nsk, with an event bus you can overcome limitations of IPC, but this brings a "fun" with activity's lifecycle
  4. kotlin brings kotlinx.serialization into the game, not much experience on my side, but sure something you can evaluate(performance and data size)

Independently of selected solution to your problem, I would recomend to use Parcelable instead of Seriazable for Intent, mainly for performance reasons, reflection is still an issue and I can barely remember having lint warnings. For Parcelable with Kotlin there is indeed a handy solutionwith Parcelize annotation provided by Kotlin Android Extensions library.

Simple object looks like this

@Parcelize
class Student(val name: String, val year: Int) : Parcelable

Upvotes: 1

nsk
nsk

Reputation: 330

You can use singleton object and store your data in it. In intent you can pass some key (Int or maybe String) to get your data from singleton in receiver activity.

Also there are implementations of event bus pattern, that are applicable for same reason.

Upvotes: 2

Related Questions