Extension functions that simplify common mapping operations in RxJava streams, especially when wrapping nullable values in Optionals.
This project is intended as a companion library to rx-mvi as it reduces some of the boilerplate when observing partial state updates.
Consider an Observable
stream that emits State
objects:
data class State(
val foo: String = "foo",
val bar: String? = null
)
fun state(): Observable<State> {
return Observable.just(
State(),
State(bar = "initialized"),
State(foo = "changed", bar = "initialized")
)
}
state().subscribe { println(it) }
// --> State(foo=foo, bar=null)
// --> State(foo=foo, bar=initialized)
// --> State(foo=changed, bar=null)
Map to one property of the state and ensure that subsequently emitted values are distinct.
The passed lambda acts as an extension function with the Observable's type as it's receiver and thus allows to access properties without having to refer to the lambda parameter.
state().mapDistinct { foo }
.subscribe { println(it) }
// --> foo
// --> changed // skips middle value with identical `foo`
Map to one property of the state and ensure that only the first value is observed
state().mapOnce { foo }
.subscribe { println(it) }
// --> foo // completes after one value
Map to one nullable property of the state and wrap in Optional
state().mapOptional { bar }
.subscribe { println(it) }
// --> None
// --> Some(initialized)
// --> None
Map to one nullable property of the state, wrap in Optional
, and ensure
that only first value is observed
state().mapOptionalOnce { bar }
.subscribe { println(it) }
// --> None
Map to one nullable property of the state and wrap in Optional
and ensure that subsequently emitted values are distinct
state().mapOptionalDistinct { bar }
.subscribe { println(it) }
// --> None
// --> Some(initialized)
Map to one nullable property of the state and wrap in Optional
,
then filter for Some
state().mapSome { bar }
.subscribe { println(it) }
// --> initialized // skips `None`
// --> initialized // `foo` changed, causing another emission
Map to one nullable property of the state and wrap in Optional
,
then filter for Some
and ensure that subsequently emitted values are distinct
state().mapSomeDistinct { bar }
.subscribe { println(it) }
// --> initialized // skips `None` and unrelated change of `foo`
Map to one nullable property of the state and wrap in Optional
,
then filter for Some
and ensure that only the first value is observed
state().mapSomeOnce { bar }
.subscribe { println(it) }
// --> initialized // skips `None` and completes after one emission
dependencies {
implementation "cc.femto:rx-mapping-extensions:0.4"
}
Requires the JitPack repository:
repositories {
maven { url "https://jitpack.io" }
}