2

I have problem working with MutableStateFlow, I cannot understand how it is working or I am mistaken somewhere. For example purpose I created simpler classes to get the idea what I am doing.

First I have data class which holds the values and controller which update values in the data class


data class ExampleUiState(
    val dataFlag: Boolean = false
)

class ExampleController {
    private val _exampleUiState = MutableStateFlow(ExampleUiState())
    val exampleUiState = _exampleUiState.asStateFlow()

    fun onChangeFlag(flag: Boolean) {
        _exampleUiState.update { it.copy(dataFlag = flag) }
    }
}

I am using koin, and I created Example controller singleton. Second I am injection it in my ViewModel where I have two functions there

class ExampleViewModel(
    private val exampleController: ExampleController
) : ViewModel() {

    val exampleUiState = exampleController.exampleUiState.stateIn(
        viewModelScope,
        SharingStarted.WhileSubscribed(5000),
        ExampleUiState()
    )

    //called second
    private fun useFlagInViewModelFun() {
        //here the value is not updated
        exampleUiState.value.dataFlag
    }

    //called first from UI
    fun changeValueFromUi(flag: Boolean) {
        //change it from default false to true
        exampleController.onChangeFlag(flag)
        useFlagInViewModelFun()
    }
}

The idea is when I call changeValueFromUi from some compose function, I update the value with my controller function, and after it I call other function where I want to use already updated state of data class, but I don't get the correct value.

Where I am mistaken?

Is there any time needed for onChangeFlag() to react and update the value?

Am I mistaken the way that I am trying to get the value after exampleUiState.value.dataFlag ?

Svilen Rusev
  • 309
  • 4
  • 15
  • 2
    I used your code with [this view](https://gist.github.com/PhilipDukhov/ef148bf0753478f89b0325e9b534e911) and it works fine: I added log to `useFlagInViewModelFun` and new value is available immediately after update. Works fine on both Compose **1.1.1** and **1.2.0-alpha04**. p.s. Not sure why you use `stateIn`, it should convert a cold `Flow` to `StateFlow` and you already have a state flow. But either way, it doesn't change anything. – Phil Dukhov Mar 24 '22 at 03:41
  • As I know `stateIn` converts it to hot flow, also I tried to inject ` ExampleController` in another viewModel and create the same function there, I did make it singleton, but now there the value is not updating, have any ideas why? – Svilen Rusev Mar 24 '22 at 05:36
  • 1
    It's hard to guess without a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). As I said, your code works fine to me. – Phil Dukhov Mar 24 '22 at 05:46

0 Answers0