How can I get the latest value of a Flow
? I don't have a StateFlow
where I need that latest value. This is the condensed scenario:
There is a repository exposing a StateFlow
val repositoryExposedStateFlow: StateFlow<SomeType> = MutableStateFlow(...)
Additionally there are mappers transforming that StateFlow
like
val mappedFlow: Flow<SomeOtherType> = repositoryExposedStateFlow.flatMapLatest { ... }
mappedFlow
is no StateFlow
anymore, but just a Flow
. Thus, I cannot get the latest/current value as I can when there's StateFlow
.
Anyhow, I need the latest value in that Flow
at some point. Since this point is not in a ViewModel
, but some Use Case implementation, I cannot simply perform a stateIn
and hold the latest value in the ViewModel
all the time the ViewModel
is alive -- otherwise I had to pass on the value to all Use Cases. Actually, within a Use Case I trigger a network refresh which leads to emitting of new values on the StateFlow
and thus on the mappedFlow
, too.
In the Use Cases I have CoroutineScopes
though. So I came up with
suspend fun <T> Flow<T>.getState(): T {
return coroutineScope {
val result = stateIn(
scope = this
).value
coroutineContext.cancelChildren()
result
}
}
Without using coroutineContext.cancelChildren()
the method will never return, because coroutineScope
blocks the caller until all child coroutines have finished. As stateIn
never finishes, I manually cancel all children.
Apparently this is a bad thing to do.
But how can I solve this problem in a better way? In my perception the problem arises from StateFlow
mapping resulting in regular Flow
instances.