Just a simple confirmation. The collect of the stateflow in following code will ran in whatever scope the created flow is collected and will be properly cancelled when the collecting flow is cancelled?
Copy code
fun <T> StateFlow<T>.withPrevious(): Flow<Pair<T?, T>> {
return flow {
var previous: T? = null
this@withPrevious.onEach {
emit(Pair(previous, it))
previous = it
}.collect()
}
}
c
Circusmagnus
12/08/2020, 12:37 PM
I think yes, but code would be a bit more streamlined with:
Copy code
fun <T> Flow<T>.withPrevious(): Flow<Pair<T?, T>> {
return flow {
var previous: T? = null
collect { value ->
emit(Pair(previous, it))
previous = it
}
}
}
Circusmagnus
12/08/2020, 12:40 PM
You are trying to diff between emissions by chance? I tried to submit an
The source is a stateflow but on some case I need to filter to only get changes for a subpart of the stateflow hence the need for previous value to be able to compare.
Tolriq
12/08/2020, 2:03 PM
Anywaythanks for the confirmation and improved code.