Last active
February 28, 2019 12:10
-
-
Save juanchosaravia/0b61204551d4ec815bbf to your computer and use it in GitHub Desktop.
How to use Parcelable in Kotlin v1.0.0-beta-4589
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
// ------------ Helper extension functions: | |
// Inline function to create Parcel Creator | |
inline fun <reified T : Parcelable> createParcel(crossinline createFromParcel: (Parcel) -> T?): Parcelable.Creator<T> = | |
object : Parcelable.Creator<T> { | |
override fun createFromParcel(source: Parcel): T? = createFromParcel(source) | |
override fun newArray(size: Int): Array<out T?> = arrayOfNulls(size) | |
} | |
// custom readParcelable to avoid reflection | |
fun <T : Parcelable> Parcel.readParcelable(creator: Parcelable.Creator<T>): T? { | |
if (readString() != null) return creator.createFromParcel(this) else return null | |
} | |
// ------------ Classes: | |
data class RedditNews( | |
val after: String, | |
val before: String, | |
val news: List<RedditNewsItem>) : Parcelable { | |
companion object { | |
val CREATOR = createParcel { RedditNews(it) } | |
} | |
protected constructor(parcelIn: Parcel) : this( | |
parcelIn.readString(), | |
parcelIn.readString(), | |
listOf<RedditNewsItem>().apply { | |
parcelIn.readTypedList(this, RedditNewsItem.CREATOR) | |
} | |
) | |
override fun writeToParcel(dest: Parcel, flags: Int) { | |
dest.writeString(after) | |
dest.writeString(before) | |
dest.writeTypedList(news) | |
} | |
override fun describeContents() = 0 | |
} | |
data class RedditNewsItem( | |
val author: String, | |
val title: String, | |
val numComments: Int, | |
val created: Long, | |
val thumbnail: String, | |
val url: String | |
) : Parcelable { | |
companion object { | |
val CREATOR = createParcel { RedditNewsItem(it) } | |
} | |
protected constructor(parcelIn: Parcel) : this( | |
parcelIn.readString(), | |
parcelIn.readString(), | |
parcelIn.readInt(), | |
parcelIn.readLong(), | |
parcelIn.readString(), | |
parcelIn.readString() | |
) | |
override fun writeToParcel(dest: Parcel, flags: Int) { | |
dest.writeString(author) | |
dest.writeString(title) | |
dest.writeInt(numComments) | |
dest.writeLong(created) | |
dest.writeString(thumbnail) | |
dest.writeString(url) | |
} | |
override fun describeContents() = 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment