https://kotlinlang.org logo
#coroutines
Title
# coroutines
z

Zoltan Demant

10/11/2023, 6:57 AM
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

Sam

10/11/2023, 7:59 AM
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

Zoltan Demant

10/11/2023, 8:15 AM
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

Sam

10/11/2023, 9:09 AM
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

Zoltan Demant

10/11/2023, 11:48 AM
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!
3 Views