How do I add log statements to a stateflow?


I have the following simple code in my viewmodel:

    private val _foo = MutableStateFlow(0f)
    val foo = _foo.asStateFlow()

In several locations in the viewmodel _foo is updated:

    _foo.update { newFloat }

I want to add a log everytime foo is updated (as I'm chasing a bug). I'm pretty sure there's a simple way to add a block of code somewhere, but I can't figure it out, nor can I find examples.

0
Aug 26 at 5:44 PM
User AvatarSMBiggs
#android#kotlin#logging#kotlin-stateflow

Accepted Answer

You can use onEach to perform an action for every value in the Flow:

val foo = _foo
    .onEach { println(it) }
    .stateIn(viewModelScope, SharingStarted.Eagerly, 0f)

onEach only returns a simple Flow, so stateIn is needed to make it a StateFlow again. It creates a new coroutine for that, which would be unnecessary when using a MutableStateFlow directly - you should probably only do it for debugging, not in your production code.

Alternatively, you can start a new Flow collection by adding this after the declaration of _foo:

init {
    viewModelScope.launch { _foo.collect { println(it) } }
}
User Avatartyg
Aug 26 at 9:31 PM
2