Just a simple confirmation. The collect of the sta...
# coroutines
t
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
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
        }
    }
}
You are trying to diff between emissions by chance? I tried to submit an
windowed
operator for that once: https://github.com/Kotlin/kotlinx.coroutines/pull/1558
t
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.
Anywaythanks for the confirmation and improved code.