Use Retrolambda and RxJava to Write Less Code
Retrolambda lets you use lambda functions on the Android if you are using older Java versions (prior to Java 8). Let’s examine the difference:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handleClick(v));
}
});
The same code using Retrolambda:
button.setOnClickListener(view -> handleClick(v));
RxJava is lightweight Java VM implementation of the ReactiveX(Reactive Extensions). It is a single JAR library and supports Java 6 or higher and JVM-based languages. RxJava uses a different approach than classic programming for composing asynchronous and event-based programs by using observable sequences. Let’s examine how we could implement the following behavior:
- Every 10 seconds, make a request to the backend and fetch rate information.
- In the case of an error, retry three times with a delay of three seconds between each try.
The code using RxJava:
mService = ServiceFactory.createRetrofitService(RatesService.class,
RatesService.SERVICE_ENDPOINT);
mRatesObservable = Observable.interval(0, 10, TimeUnit.SECONDS)
.flatMap(n ->
mService.getRates()
.retryWhen(new RetryWithDelay(3, 3000))
.subscribeOn(Schedulers.io()));
mRatesObservable = mRatesUpdater.getRates().doOnNext(rates -> updateRates(rates));
// Stop requests
mRatesObservable.unsibscribe();
In less than ten lines of code, we implemented a custom behavior with the network response. Try to imagine how many lines of code you would need with classic Java code, using callbacks, services, and loaders.
Jack and Jill and Java 8
With Retrolambda, though, keep in mind that it could be deprecated soon because of Jack and Jill, an experimental tool for Android that is available in the N developer preview that provides Java 8 features out-of-the-box. Keep an eye on the updates from Google closely about the Jack and Jill, and switch to native implementation as soon as it is ready.
Contributors
Dmitry Ryazantsev
Dmitry is an Android developer with more than six years of experience who communicates well and always tries to find the best tech that suits the project. He's experienced with Git, Lua (Corona SDK), RxJava, Dagger, etc. He's worked with a large team to develop the Yandex browser that has more than 10 million installations. He's also developed his own projects: a game with 250,000 installations and published several other apps.
Show More