Yes, there is a simple solution to this that I've been using in my projects. The idea is to wrap any reference types/objects in a warper class that is Parcalabe
and Serializable
without actually implementing marshaling of the underlying reference type. Here is the wrapper class and how to use it without causing any potential memory leak:
@Parcelize @kotlinx.serialization.Serializable
data class TrackedReference<ReferenceType: Any> private constructor(
private var uniqueID: Int = -1
) : Serializable, Parcelable {
constructor(reference: ReferenceType) : this() {
uniqueID = System.identityHashCode(this)
referenceMap.set(uniqueID, reference)
}
val get: ReferenceType?
get() = referenceMap.get(uniqueID) as? ReferenceType
fun removeStrongReference() {
get?.let { referenceMap.set(uniqueID, WeakReference(it)) }
}
companion object {
var referenceMap = hashMapOf<Int, Any>()
private set
}
}
Any object can be wrapped in a TrackedReference
object and passed as serializable or parcelable:
class ClassA {
fun doSomething { }
}
// Add instance of ClassA to an intent
val objectA = ClassA()
intent.putExtra("key", TrackedReference(objectA))
You can also pass a weak
or soft
reference depending on the use case.
Use case 1:
The object (in this case objectA
) is not guaranteed to be in memory by the time the receiver activity needs to use it (e.g. might be garbage collected).
In this case, the object is kept in memory until you explicitly remove the strong reference.
Pass in an Intent
or Bundle
inside this wrapper and accesse in a straightforward manner, e.g. (psuedocode)
class ClassA {
fun doSomething { }
}
// Add instance of ClassA to an intent
val objectA = ClassA()
intent.putExtra("key", TrackedReference(objectA))
// Retrieve in another activity
val trackedObjectA = intent.getSerializable("key") as TrackedReference<ClassA>
trackedObjectA.get?.doSomething()
// Important:- to prevent potential memory leak,
// remove *strong* reference of a tracked object when it's no longer needed.
trackedObjectA.removeStrongReference()
Use case 2:
The object is guaranteed to be in memory when needed, e.g. an activity that is housing a fragment is guaranteed to remain in memory for the lifecycle of the fragment.
Or, we do not care if the object is garbage collected, and we do not want to be the reason for its existence. In this case, pass a weak
or soft
reference when initializing a TrackedReference
instance:
// Removing the strong reference is not needed if a week reference is tracked, e.g.
val trackedObject = TrackedReference(WeakReference(objectA))
trackedObject.get?.doSomething()
Its best to understand why Intent
requires Parcelable
or Serializable
and what's the best way to use this workaround in a given scenario.
It's certainly not ideal to serialize objects to allow delegation or callback communication between activities.
Here is the documentation on Intent
but simply put, an Intent
is passed to the Android System which then looks-up what to do with it and in this case starts the next Activity (which can be another app as far as the Android System receiving the intent is concerned). Therefore, the system needs to make sure that everything inside an intent can be reconstructed from parcels.
Rant:
IMO, Intent
as a higher level abstraction for IPC (Inter Process Communication) maybe convenient and efficient internally but at the cost of these limitations.
It's maybe comparing Apples to oranges but in iOS, ViewControllers (similar to Activities) are like any class and can be passed any Type
(value or reference) as an argument. The developer is then responsible to avoid potential reference-cycles that might prevent ARC (memory management) to free unused references.