Skip to content

Instantly share code, notes, and snippets.

@eneim
Created January 22, 2022 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eneim/d87cf952efd6b58e100e8acc81206b00 to your computer and use it in GitHub Desktop.
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.
/**
* 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