Skip to content

Instantly share code, notes, and snippets.

@AchrafAmil
Created June 17, 2021 15:59
Show Gist options
  • Save AchrafAmil/d22c36f5be3d49c5e0cff76c275526b1 to your computer and use it in GitHub Desktop.
Save AchrafAmil/d22c36f5be3d49c5e0cff76c275526b1 to your computer and use it in GitHub Desktop.
Operator to alter a first flow's last emitted value whenever the second flow emits. Transformation will take last value from both as in combine
/**
* Will emit all values from Flow<T1>, plus those from Flow<T2> after transformation giving the latest from Flow<T1>.
*
*/
fun <T1, T2> Flow<T1>.alterOn(other: Flow<T2>, transform: suspend (a: T1, b: T2) -> T1): Flow<T1> = channelFlow {
coroutineScope {
val thisLatestValue = AtomicReference<T1?>()
launch {
other.collect { t2 ->
thisLatestValue.get()?.let { t1 ->
send(transform(t1, t2))
}
}
}
collect { t1 ->
thisLatestValue.set(t1)
send(t1)
}
}
}
// (Can also be acheived using flatMapLatest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment