public interface RxBox<T> extends RxGetter<T>, Box<T>
Modifier and Type | Interface and Description |
---|---|
static class |
RxBox.Default<T>
Standard implementation of an
RxBox . |
Box.Dbl, Box.Int, Box.Nullable<T>
Modifier and Type | Method and Description |
---|---|
default RxBox<T> |
enforce(Function<? super T,? extends T> getMapper)
Provides a mechanism for enforcing an invariant.
|
static <T> RxBox<T> |
from(RxGetter<T> getter,
Consumer<T> setter)
Creates an
RxBox which implements the "getter" part with RxGetter , and the setter part with Consumer . |
default <R> RxBox<R> |
map(Function<? super T,? extends R> getMapper,
Function<? super R,? extends T> setMapper)
Maps one
RxBox to another RxBox . |
static <T> RxBox<T> |
of(T initial)
Creates an
RxBox with the given initial value. |
default RxGetter<T> |
readOnly()
Returns a read-only version of this
RxBox . |
combineLatest, from, map
asObservable
default <R> RxBox<R> map(Function<? super T,? extends R> getMapper, Function<? super R,? extends T> setMapper)
RxBox
to another RxBox
.default RxBox<T> enforce(Function<? super T,? extends T> getMapper)
For example, let's say that there is an RxBox<List<T>>
which represents
a user's multiselection in some widget. You would like the user to select
a pair of values - you want to enforce that the selection doesn't grow
beyond 2 elements.
You could write code like this:
RxBox<List<T>> selection = widget.rxSelection();
RxGetter<List<T>> onlyPairs = selection.map(list -> list.stream().limit(2).collect(Collectors.toList()));
Rx.subscribe(onlyPairs, selection);
But there's a subtle bug in this code. Because RxGetter
and RxBox
only
fire their observables when their value changes, the selection invariant won't be enforced
unless onlyPairs
actually changes. It's easy to fix:
RxBox<List<T>> selection = widget.rxSelection();
Observable<List<T>> onlyPairs = selection.asObservable().map(list -> list.stream().limit(2).collect(Collectors.toList()));
Rx.subscribe(onlyPairs, selection);
But there's still a problem - selection
will momentarily contain values which violate the invariant. That
means you can't write listener code that relies on the invariant being true. Which is why the enforce()
method exists:
RxBox<List<T>> onlyPairs = widget.rxSelection().enforce(list -> list.stream().limit(2).collect(Collectors.toList()));
This creates a new RxBox
which will always satisfy the invariant, and it will enforce this invariant
on the original RxBox
.static <T> RxBox<T> of(T initial)
RxBox
with the given initial value.