Usage

You might think that setting all Retrolambda can be just too much trouble for very little gain. Nothing could be further from the truth and it will be obvious after we take a look at a few examples of code.

Compare the following two samples of code. The first sample is as follows:

Observable.just("1")
.subscribe(new Consumer<String>() {
@Override
public void accept(String e) {
Log.d("APP", "Hello " + e);
}
});

Here's the next sample:

Observable.just("1")
.subscribe(e -> Log.d("APP", "Hello " + e));

The latter is much more concise, but might fail to show the scale of the problem of the former approach. This example might be much better at doing so:

Observable.just("1")
.map(new Function<String, String>() {
@Override
public String apply(String s) {
return s + "mapped";
}
})
.flatMap(new Function<String, Observable<String>>() {
@Override
public Observable<String> apply(String s) {
return Observable.just("flat-" + s);
}
})
.doOnNext(new Consumer<String>() {
@Override
public void accept(String s) {
Log.d("APP", "on next " + s);
}
})
.subscribe(new Consumer<String>() {
@Override
public void accept(String e) {
Log.d("APP", "Hello " + e);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
Log.d("APP", "Error!");
}
});

Now, take a look at this:

Observable.just("1")
.map(s -> s + "mapped")
.flatMap(s -> Observable.just("flat-" + s))
.doOnNext(s -> Log.d("APP", "on next " + s))
.subscribe(e -> Log.d("APP", "Hello " + e),
throwable -> Log.d("APP", "Error!"));

That's 24 lines saved! 

The observable flows can get pretty complicated and long, so these lines add up pretty quickly.

If you are stuck with an old version of Java, there are other means to make these flows clear; we will cover more about this in the later chapters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.241.250