Skip to content

Instantly share code, notes, and snippets.

@Ramasubramanian
Created March 10, 2017 08:55
Show Gist options
  • Save Ramasubramanian/86e48cd06c6a400cc55980968916d67e to your computer and use it in GitHub Desktop.
Save Ramasubramanian/86e48cd06c6a400cc55980968916d67e to your computer and use it in GitHub Desktop.
A generic kotlin utility class to convert a realm list with parceler
/**
* 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