I have following setup:
Kotlin data class:
data class Error(val throwable: Throwable, val reloadAction: (() -> Unit)? = null) : Serializable
Initialization of class:
val instance = Error(throwable,this::loadData)
Where this
is ViewModel
from Android Architecture components
When I'm passing this data class to parcelable:
parcel.writeSerializable(instance as Serializable)
I get following exception:
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.mypackagename.Error)
at android.os.Parcel.writeSerializable(Parcel.java:1468)
at com.mypackagename.CustomView$Companion$SavedState.writeToParcel(CustomView.kt:177)
...
Caused by: java.io.NotSerializableException: com.mypackagename.ExampleViewModel
In this question: Is there a way to pass a function reference between activities? is following answer:
It will actually be Serializable if it is a function reference (SomeClass::someFunction) or a lambda. But it might not be, if it is some custom implementation of the functional interface () -> Unit, so you should check that and handle the cases when it's not.
Is this my case? Or data class cannot be serialized when function is function of non serializable object (ViewModel)? Are there any other possibilities how to pass function literal as Serializable inside data class?