How to make RealmList Parcelable?

2019-08-23 05:06发布

@Parcelize open class TestClass(
        @SerialName("title")   
        var title: String,
        @SerialName("list")   
        var list: RealmList<String>    
) : RealmObject() { ... }

How can I parcelize "list" variable in this implementation?
It says, that it's not possible to parcel this type of value even if I add @RawValue.
What's the alternative here? An example with explanation would be flawless.

1条回答
欢心
2楼-- · 2019-08-23 05:38

Similarly to this approach, you can do

fun Parcel.readStringRealmList(): RealmList<String>? = when {
    readInt() > 0 -> RealmList<String>().also { list ->
        repeat(readInt()) {
            list.add(readString())
        }
    }
    else -> null
}

fun Parcel.writeStringRealmList(realmList: RealmList<String>?) {
    writeInt(when {
        realmList == null -> 0
        else -> 1
    })
    if (realmList != null) {
        writeInt(realmList.size)
        for (t in realmList) {
            writeString(t)
        }
    }
}

Then you can do

object StringRealmListParceler: Parceler<RealmList<String>?>  {
    override fun create(parcel: Parcel): RealmList<String>? = parcel.readStringRealmList()

    override fun RealmList<String>?.write(parcel: Parcel, flags: Int) {
        parcel.writeStringRealmList(this)
    }
}

Now you can do

@Parcelize 
open class TestClass(
        @SerialName("title")   
        var title: String = "",
        @SerialName("list")   
        var list: @WriteWith<StringRealmListParceler> RealmList<String>? = null
) : RealmObject(), Parcelable { ... }
查看更多
登录 后发表回答