How would you refactor this into a cold flow? ```p...
# coroutines
z
How would you refactor this into a cold flow?
Copy code
private val version = MutableStateFlow(0L).also { state ->
    scope.launch {
        registry.repositories.map { repository ->
            repository.changes
        }.merge().collect {
            state.update { version ->
                version.inc()
            }
        }
    }
}
s
Since you asked about a cold flow, I guess that means you don't need it to be a
StateFlow
? A bit more info would help, but it looks like this is just:
Copy code
val version = registry.repositories
    .flatMapConcat { it.changes }
    .runningFold(0L) { acc, _ -> acc + 1 }
z
No need for a StateFlow. Part of the challenge for me is that each
repository.change
is a
Flow<...>
and while I can use
combine(flows)
that will only emit after each flow has emitted a value I believe?
s
If you use
flatMapConcat
(or the now-deprecated
merge
) it will collect all the changes from the first repository before moving on to the next repository. If you want to collect changes from multiple repositories at the same time, you could use
flatMapMerge
instead.
z
Copy code
registry.repositories.map { it.changes }.merge().scan(0L) { version, _ ->
    version + 1
}
👍🏽 Thanks for the help, this clearly shows me that despite how much I work with and read about coroutines, I still have so much more to learn!