An operator can be used to manipulate the flow of objects from Observable
to Subscriber
.
Observable<Integer> integerObservable = Observable.just(1, 2, 3); // creating a simple Integer observable
Subscriber<String> mSubscriber = new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println("onCompleted called!");
}
@Override
public void onError(Throwable throwable) {
System.out.println("onError called");
}
@Override
public void onNext(String string) {
System.out.println("onNext called with: " + string);
}
}; // a simple String subscriber
integerObservable
.map(new Func1<Integer, String>() {
@Override
public String call(Integer integer) {
switch (integer) {
case 1:
return "one";
case 2:
return "two";
case 3:
return "three";
default:
return "zero";
}
}
}).subscribe(mSubscriber);
The output would be:
onNext called with: one
onNext called with: two
onNext called with: three
onCompleted called!
The map
operator changed the Integer
observable to a String
observable, thereby manipulating the flow of objects.
Operator Chaining
Multiple operators can be chained
together to for more powerful transforms and manipulations.
integerObservable // emits 1, 2, 3
.map(i -> i + 10) // adds 10 to each item; emits 11, 12, 13
.filter(i -> i > 11) // emits items that satisfy condition; 12, 13
.last() // emits last item in observable; 13
// unlimited operators can be added ...
.subscribe(System.out::println); // prints 13
Any number of operators can be added in between the Observable
and Subscriber
.