Created
March 10, 2017 08:55
-
-
Save Ramasubramanian/86e48cd06c6a400cc55980968916d67e to your computer and use it in GitHub Desktop.
A generic kotlin utility class to convert a realm list with parceler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Java code from https://gist.github.com/patloew/bc32a2a1a3c0097e9c7020192fb2c78f | |
* used and converted to Kotlin with some modifications | |
*/ | |
open class RealmListParcelConverter<T> : TypeRangeParcelConverter<RealmList<T>, RealmList<T>> where T : io.realm.RealmObject{ | |
override fun toParcel(input: RealmList<T>?, parcel: Parcel) { | |
if (input == null) { | |
parcel.writeInt(NULL) | |
} else { | |
parcel.writeInt(input.size) | |
for (item in input) { | |
parcel.writeParcelable(Parcels.wrap(item), 0) | |
} | |
} | |
} | |
override fun fromParcel(parcel: Parcel): RealmList<T> { | |
val size = parcel.readInt() | |
val list = RealmList<T>() | |
for (i in 0..size - 1) { | |
val parcelable = parcel.readParcelable<Parcelable>(javaClass.classLoader) | |
list.add(Parcels.unwrap<Any>(parcelable) as T) | |
} | |
return list | |
} | |
companion object { | |
private val NULL = -1 | |
} | |
} | |
//Usage: class FooParcelConverter: RealmListParcelConverter<Foo>() | |
//Foo: RealmObject() {...} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment