https://kotlinlang.org logo
Title
j

John Aoussou

12/17/2021, 3:04 PM
I'd like to know the simplest way to make a StateFlow directly depend on another. For example, let's say in my viewmodel I have:
private val _stateFlow1 = MutableStateFlow(0)
Is there a way to define
_stateFlow2
so that
_stateFlow2.value = _stateFlow1.value * _stateFlow1.value
?
s

Stew Boling

12/17/2021, 3:29 PM
val _stateFlow1 = MutableStateFlow(0)
val _stateFlow2 = _stateFlow1.map { it * it }.stateIn(viewModelScope)
That is if you need _stateFlow2 to be a StateFlow otherwise you can drop
stateIn()
j

John Aoussou

12/17/2021, 3:42 PM
Don't you need a coroutine do that?
s

Stew Boling

12/17/2021, 3:43 PM
Not externally, that is why stateIn() requires a scope so it can launch an internal coroutine context.
j

John Aoussou

12/17/2021, 3:44 PM
Well, I had tried that but it's giving me
Suspend function 'stateIn' should be called only from a coroutine or another suspend function
s

Stew Boling

12/17/2021, 3:46 PM
Oops wrong
stateIn()
there is a non-suspending one
val _stateFlow1 = MutableStateFlow(0)
val _stateFlow2 = _stateFlow1.map { it * it }.stateIn(viewModelScope, SharingStarted.Eagerly, _stateFlow1.value)
:thank-you: 1
j

John Aoussou

12/17/2021, 3:50 PM
Awesome, would never have figured out that one! 🙇‍♂️
👍 1