Home > Mobile >  Why can't I use the update function to update a flow in Kotlin?
Why can't I use the update function to update a flow in Kotlin?

Time:04-21

I hope to use Code A to update a flow, but I find the Flow soundDensityState isn't updated.

But Code B workes, what's problem with Code A ?

Code A

private val _soundDensityState = MutableStateFlow(MSoundDensity() )
val soundDensityState = _soundDensityState.asStateFlow()

fun beginSoundDensity(filename: String){       
    myJob = viewModelScope.launch(Dispatchers.IO) {
        aSoundMeter.getMSoundDensity().cancellable().collect {
            _soundDensityState.update { it }
        }
    }
}

Code B

private val _soundDensityState = MutableStateFlow(MSoundDensity() )
val soundDensityState = _soundDensityState.asStateFlow()

fun beginSoundDensity(filename: String){
    myJob = viewModelScope.launch(Dispatchers.IO) {
        aSoundMeter.getMSoundDensity().cancellable().collect {
            _soundDensityState.value =it 
        }
    }
}

CodePudding user response:

it in that lambda is a parameter of update holding the current value of the StateFlow. It is shadowing the it of the collect lambda.

CodePudding user response:

StateFlow is not updating because of the name shadowing, as parameters of update and collect lambdas have the same name it.

It can be resolved by giving either of the lambda a different name. Change the name of collect lambda to soundDensity and use that in update.

private val _soundDensityState = MutableStateFlow(MSoundDensity() )
val soundDensityState = _soundDensityState.asStateFlow()

fun beginSoundDensity(filename: String){
    myJob = viewModelScope.launch(Dispatchers.IO) {
        aSoundMeter.getMSoundDensity().cancellable().collect { soundDesity ->
            _soundDensityState.update { soundDesity }
        }
    }
}
  • Related