https://kotlinlang.org logo
Title
t

Tolriq

12/08/2020, 10:02 AM
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?
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:
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

Tolriq

12/08/2020, 1:59 PM
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.