emreturka
emreturka

Reputation: 876

How to parcelize a function in kotlin

I want to make a parcelable data class to put bundle. Also this data class containing a function that I will invoke. But when I put the app back , I am getting exception with parcelize. Here is my data class that parcelable,

@Parcelize
data class TransactionConfirmData(
val title: String,
@StringRes val cancelBtnLabel: Int
@StringRes val confirmBtnLabel: Int
val confirmElements: Map<String, String>,
val customConfirmDataList: List<CustomTransactionConfirmData> = emptyList(),
val requestMethodId: Int,
@NavigationRes val cancelDestination: Int = 0,
val contentStructure: 
    TransactionBodyContentCaseTransactionBodyContentCase.BASE_CONFIRM,
 @IgnoredOnParcel val onPressFunction: Serializable

) : Parcelable {

fun onPressOkey() = onPressFunction as () -> Unit

companion object {
    fun create(
        title: String,
        @StringRes cancelBtnLabel: Int = R.string.bottom_sheet_behavior
        @StringRes confirmBtnLabel: Int = R.string.bottom_sheet_behavior
        confirmElements: Map<String, String>,
        customConfirmDataList: List<CustomTransactionConfirmData> = emptyList(),
        requestMethodId: Int,
        @NavigationRes  cancelDestination: Int = 0,
        contentStructure: TransactionBodyContentCase = 
               TransactionBodyContentCase.BASE_CONFIRM,
        onPressFunction: ()->Unit = {}
    ): TransactionConfirmData = TransactionConfirmData(
        title,
        cancelBtnLabel,
        confirmBtnLabel,
        confirmElements,
        customConfirmDataList,
        requestMethodId,
        cancelDestination,
        contentStructure,
        onPressFunction as Serializable
    )
}

}

But this is not working.

Upvotes: 2

Views: 1720

Answers (2)

yerih iturriago
yerih iturriago

Reputation: 1

The key is the annotation @IgnoredOnParcel.

Upvotes: 0

emreturka
emreturka

Reputation: 876

I solved that with a listener class like below;

class Listener(val clickAction:()->Unit):Parcelable{
   fun onClick() = clickAction()
}

then you can create the field like this in your data class;

val onPressOkey:Listener = Listener {}

Also you can call this onPressOkey ;

 yourDataClass.onPressOkey.onClick()

Upvotes: 0

Related Questions