I am trying to put a parcelable in a bundle that I want to send to a navigation component. My data class is,
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Post(
val name: String,
val slug: String,
val thumbnail:String
) : Parcelable
<argument
android:name="post"
app:argType="com.example.blog.models.Post"
app:nullable="true" />
val post: MutableLiveData<List<Post>> by lazy { MutableLiveData<List<Post>>() }
// after api call, the body of the response which is a list of Post objects
// are attached to viewmodel.
post.postValue(response.body())
// after observing the changes in the post variable in viewmodel,
// a bundle is created which is added to the navigation..
val bundle = Bundle()
bundle.putParcelable("post", post.value)
Editor
Type mismatch.
Required: Parcelable?
Found: List<Post>?
Build
Type mismatch: inferred type is List<Post>? but Parcelable? was expected
Firs of all you need to use LiveData which will wrap your MutableLiveData.
fun getPosts(): LiveData<List<Post>> {
return post
}
What you want to pass to your Bundle is the List directly, but wrapped in a Serialized implementation of List. That's why the code below wraps the value of your LiveData in an ArrayList.
So, you can do this instead:
bundle.putParcelableArrayList("post", arrayListOf(getPosts().value));
To read it back:
bundle.getParcelableArrayList("post") as List<Post>?