Created
January 22, 2022 13:48
-
-
Save eneim/d87cf952efd6b58e100e8acc81206b00 to your computer and use it in GitHub Desktop.
A Flow emits a pair of the original Flow's latest value and its previous value.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Given a Flow A, returns a [Flow] that emits a pair of the latest value emitted by A (as the | |
* second value of the pair), and the previous value emitted before (as the first value of the | |
* pair). | |
* | |
* Example | |
* ``` | |
* val originalFlow = flowOf(1, 2, 3, 4) | |
* originalFlow.flowWithPrevious().collect { (l, r) -> | |
* println("Left: $l, Right: $r") | |
* } | |
* ``` | |
* | |
* Output: | |
* ``` | |
* Left: null, Right: 1 | |
* Left: 1, Right: 2 | |
* Left: 2, Right: 3 | |
* Left: 3, Right: 4 | |
* ``` | |
*/ | |
fun <T : Any?> Flow<T>.flowWithPrevious(): Flow<Pair<T?, T>> = flow { | |
var previousValue: T? = null | |
collect { value: T -> | |
val newPair = previousValue to value | |
previousValue = value | |
emit(newPair) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment