Checkout the previous post here
Here's how we're going to solve the item transformation problems: with operators. Operators can be used in between the source Observable
and the ultimate Subscriber
to manipulate emitted items. RxJava comes with a huge collection of operators, but its best to focus on just a handful at first.
For this situation, the map()
operator can be used to transform one emitted item into another:
Observable.just("Hello, world!")
.map(new Func1<String, String>() {
@Override
public String call(String s) {
return s + " -Dan";
}
})
.subscribe(s -> System.out.println(s));
Again, we can simplify this by using lambdas:
Observable.just("Hello, world!")
.map(s -> s + " -Dan")
.subscribe(s -> System.out.println(s));
Pretty cool, eh? Our map()
operator is basically an Observable
that transforms an item. We can chain as many map()
calls as we want together, polishing the data into a perfect, consumable form for our end Subscriber
.
[amazon_link asins='9352134664,B0784QQV4W,B073L5JB27,1484214293,B071VG1VY9,1787120422,1784399108' template='ProductCarousel' store='200' marketplace='IN' link_id='71151eab-363b-11e8-a2a4-cb611b633f41']
Here's an interesting aspect ofmap()
: it does not have to emit items of the same type as the source Observable
!
Suppose my Subscriber
is not interested in outputting the original text, but instead wants to output the hash of the text:
Observable.just("Hello, world!")
.map(new Func1<String, Integer>() {
@Override
public Integer call(String s) {
return s.hashCode();
}
})
.subscribe(i -> System.out.println(Integer.toString(i)));
Interesting - we started with a String but our Subscriber
receives an Integer. Again, we can use lambdas to shorten this code:
Observable.just("Hello, world!")
.map(s -> s.hashCode())
.subscribe(i -> System.out.println(Integer.toString(i)));
Like I said before, we want our Subscriber
to do as little as possible. Let's throw in another map()
to convert our hash back into a String:
Observable.just("Hello, world!")
.map(s -> s.hashCode())
.map(i -> Integer.toString(i))
.subscribe(s -> System.out.println(s));
Would you look at that - our Observable
and Subscriber
are back to their original code! We just added some transformational steps in between. We could even add my signature transformation back in as well:
Observable.just("Hello, world!")
.map(s -> s + " -Dan")
.map(s -> s.hashCode())
.map(i -> Integer.toString(i))
.subscribe(s -> System.out.println(s));