Home > other >  Is it possible to have a custom setter for mutableStateOf() in Kotlin
Is it possible to have a custom setter for mutableStateOf() in Kotlin

Time:11-23

I want to do some operations two seconds after every time a certain state is set.

Code inside viewModel:

var isLoading = mutableStateOf(LoadingState.NONE)
    set(value) {
        Timber.d("Custom Setter") //Not Firing

        //Do something when the state is set to success.
        if(value.value == LoadingState.SUCCESS){
            viewModelScope.launch {
                delay(2000L)
                dispatchEvent(//some event)
            }
        }
        field = value
    }

The set{} block is not running at all. But the value is being correctly set.

When using delegation with the by keyword,

Delegated property cannot have accessors with non-default implementations

Is there a way to make custom setter work for mutableStateOf() in Jetpack Compose?.

CodePudding user response:

I think you can use snapshotFlow for this usecase. It creates a Flow from a given compose State.

var isLoading by mutableStateOf(LoadingState.NONE)
    private set

init {
    viewModelScope.launch {
        snapshotFlow { isLoading }
            .collect { 
                if(it == LoadingState.SUCCESS) {
                    delay(2000L)
                    dispatchEvent(//some event)
                }
            }
    }
}

CodePudding user response:

Building on @ArpitShukla 's answer. I think we can also use scope functions to make the code cleaner.

var isLoading by mutableStateOf(LoadingState.NONE).also{ state ->
        viewModelScope.launch {
            snapshotFlow { state }
                .collect {
                    if(it.value == LoadingState.SUCCESS) {
                        delay(2000L)
                        dispatchEvent(//Fire event)
                    }
                }
        }
    }
        private set
  • Related