If I have a StateFlow, what is the best way to map it to another StateFlow? I get a Flow back from
map
, but if I want it to be a StateFlow again I need to use
stateIn
but then I require a scope. Or is the mapped result still a stateflow?
The usecase is I have a class that I want to expose a StateFlow which is based on another one. But if I want to use
stateIn
I need to do this from a coroutine. So it becomes something like this:
interface History {
val activeLocation: StateFlow<Location>
// ...
}
class Router<R>(
private val history: History,
private val routing: Routing<R>,
private val scope: CoroutineScope
) {
lateinit var activeRoute : StateFlow<R>
private set
init {
scope.launch {
activeRoute = history.activeLocation
.map { location -> routing.getRoute(location) }
.stateIn(scope)
}
}
}
I am not sure if this is the most optimal way of doing it... I have the feeling I am overcomplicating stuff.