Skip to content

Instantly share code, notes, and snippets.

@tcw165
Created January 25, 2021 03:08
Show Gist options
  • Save tcw165/eaa59622e4bc968b5e5d85d5a33a484e to your computer and use it in GitHub Desktop.
Save tcw165/eaa59622e4bc968b5e5d85d5a33a484e to your computer and use it in GitHub Desktop.
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.ObservableTransformer
import java.util.Optional
import java.util.concurrent.atomic.AtomicReference
/**
* A transformer that remembers the last value. For observer, you'll get a pair of
* last value and current value.
*
* Note: When there's no last value remembered and initial value is null, observer
* gets current value along with a null last value.
*/
class ObservableEchoTransformer<T>(
initialValue: T? = null
) : ObservableTransformer<T, Pair<Optional<T>, T>> {
private val lastValue = AtomicReference<T?>()
override fun apply(
upstream: Observable<T>
): ObservableSource<Pair<Optional<T>, T>> {
return upstream.map { newValue: T ->
val echoResult = Pair(
Optional.ofNullable(lastValue.getAndSet(newValue)),
newValue
)
echoResult
}
}
}
/**
* Remember the last value and give you a pair of last value and current value.
*
* Note: When there's no last value remembered and initial value is null, observer
* gets current value along with a null last value.
*/
fun <T> Observable<T>.echo(
initialValue: T? = null
): Observable<Pair<Optional<T>, T>> {
return compose(ObservableEchoTransformer(initialValue))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment