Skip to content

Instantly share code, notes, and snippets.

@Takhion
Created March 13, 2019 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Takhion/b66f25fd6ecef03037ef7b6c88345eda to your computer and use it in GitHub Desktop.
Save Takhion/b66f25fd6ecef03037ef7b6c88345eda to your computer and use it in GitHub Desktop.
import android.app.Activity
import android.content.Intent
import android.os.Parcel
import android.os.Parcelable
import java.io.Closeable
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
/**
* A special [Parcelable] that carries an in-memory reference to any instance of type [T], which will obviously
* be `null` when the process is restarted, which in turn **is to be expected**.
*
* This is useful when [T] can't be parcelled, but the framework requires it as a transport vector (for example:
* passing data to an [Activity] is only possible through an [Intent], which only accepts [Parcelable] data).
*/
class RuntimeOnlyParcelable<out T : Any>
private constructor(
val id: UUID,
val payload: T?
) :
Parcelable,
Closeable {
constructor(payload: T) : this(
id = UUID.randomUUID(),
payload = payload
) {
inMemoryStorage[id] = payload
}
override fun close() {
inMemoryStorage.remove(id)
}
override fun toString() = "${RuntimeOnlyParcelable::class.java.simpleName}(id=$id, payload=$payload)"
override fun equals(other: Any?) =
when {
other === this -> true
other !is RuntimeOnlyParcelable<*> -> false
other.id == id -> true
other.payload == payload -> true
else -> false
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + (payload?.hashCode() ?: 0)
return result
}
override fun describeContents() = 0
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeLong(id.mostSignificantBits)
parcel.writeLong(id.leastSignificantBits)
}
companion object CREATOR : Parcelable.Creator<RuntimeOnlyParcelable<*>> {
private val inMemoryStorage = ConcurrentHashMap<UUID, Any>()
override fun createFromParcel(parcel: Parcel): RuntimeOnlyParcelable<*> =
UUID(
parcel.readLong(),
parcel.readLong()
).let { id ->
RuntimeOnlyParcelable(
id = id,
payload = inMemoryStorage[id]
)
}
override fun newArray(size: Int) = arrayOfNulls<RuntimeOnlyParcelable<*>>(size)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment