I'd like to know the simplest way to make a StateF...
# flow
j
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:
Copy code
private val _stateFlow1 = MutableStateFlow(0)
Is there a way to define
_stateFlow2
so that
_stateFlow2.value = _stateFlow1.value * _stateFlow1.value
?
s
Copy code
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
Don't you need a coroutine do that?
s
Not externally, that is why stateIn() requires a scope so it can launch an internal coroutine context.
j
Well, I had tried that but it's giving me
Copy code
Suspend function 'stateIn' should be called only from a coroutine or another suspend function
s
Oops wrong
stateIn()
there is a non-suspending one
Copy code
val _stateFlow1 = MutableStateFlow(0)
val _stateFlow2 = _stateFlow1.map { it * it }.stateIn(viewModelScope, SharingStarted.Eagerly, _stateFlow1.value)
🙏 1
j
Awesome, would never have figured out that one! 🙇‍♂️
👍 1