Rxbinding? You Should?or Not?

Nitin Khanna
Sep 1, 2018 · 5 min read
Photo by Adi Goldstein on Unsplash

RxJava is one of the most popular libraries for introducing responsive programming to the Android platform. In this article, I’ll show you how to set up and use some of the most popular and powerful RxAndroid modules, including handling listeners, handlers and TextWatchers libraries, and things that let you convert any Android UI events into Observable something.

Memory leaks are the worst nightmares of every Android developer. The memory leak caused by incomplete subscriptions is the biggest drawback of using RxJava in Android apps, so I will show you how to use the RxAndroid module that handles the subscription process. At the end of this article, you’ll learn how to use RxJava in any Activity or all Fragment of them to avoid the risk of any RxJava-related memory leaks.

Let’s create more responsive Android UI

The response to UI events (such as clicks, swipes, and text input) is almost an essential part of Android app development, but dealing with Android UI events is not particularly straightforward.

You will usually TextWatchers respond to UI events using a combination of listeners, handlers, and other components. Each of these components requires a lot of boilerplate code to be written, and even worse, the way these different components are implemented is inconsistent. For example, you can OnClickListenerhandle OnClickevents by the implementation :

Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Perform some work//
}
});

But, Things are different in the case of TextWatcher. Let’s see how we solve this using android core libraries :

final EditText name = (EditText) v.findViewById(R.id.name); 
//Create a TextWatcher and specify that this TextWatcher should be called whenever the EditText’s content changes//
name.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//Perform some work//
}

@Override
public void afterTextChanged(Editable s) {
}
});

and here We stuck with the Callback Hell. Yup, You read the right word Callback Hell.
This lack of consistency can add a lot of complexity to the code. If you have UI components that depend on the output of other UI components, things get more complicated! Even a simple use case, such as asking a user to enter their name into an EditText personalized TextViews text content, and TextViews need nested callbacks, which is very difficult to implement and maintain. (Someone calls the nested callback “callback hell”)

Callbacks are just the name of a convention for using JavaScript functions. There isn’t a special thing called a ‘callback’ in the JavaScript language, it’s just a convention. Instead of immediately returning some result like most functions, functions that use callbacks take some time to produce a result. The word ‘asynchronous’, aka ‘async’, just means ‘takes some time’ or ‘happens in the future, not right now’. Usually, callbacks are only used when doing I/O, e.g. downloading things, reading files, talking to databases, etc.

Obviously, the standardized way of handling UI events has the potential to greatly simplify the code, and RxBinding is a library that allows you to convert any Android View event into one by providing a binding Observable.
Once you convert the view event to Observable, it will emit UI events in the form of data streams, and you can subscribe to this data stream, just as you would subscribe to the other Observable.

Since we’ve seen how to use the Android standard to capture the click event OnClickListener, let’s see how to achieve the same result using RxBinding:

import com.jakewharton.rxbinding.view.RxView;

Button button = (Button) findViewById(R.id.button);
RxView.clicks(button)
.subscribe(aVoid -> {
//Perform some work here//
});

This approach is not only more concise, but also a standard implementation that you can apply to all UI events that occur throughout the app. For example, capturing text input is the same as capturing click event patterns:

RxTextView.textChanges(editText)
.subscribe(charSequence -> {
//Perform some work here//
});

Well, Documentation Say’s

Photo by Felipe Furtado on Unsplash

You just need to import the dependence and your build section something look like this

compile fileTree(dir: ‘libs’, include: [‘*.jar’])
androidTestCompile(‘com.android.support.test.espresso:espresso-core:2.2.2’, {
exclude group: ‘com.android.support’, module: ‘support-annotations’
})

//Add the core RxBinding library//

compile ‘com.jakewharton.rxbinding:rxbinding:2.1.1’
compile ‘com.android.support:appcompat-v7:25.3.0’

//Don’t forget to add the RxJava and RxAndroid dependencies//

compile ‘io.reactivex.rxjava2:rxandroid:2.0.1’
compile ‘io.reactivex.rxjava2:rxjava:2.0.5’
testCompile ‘junit:junit:4.12’

In Rxbinding Naming conventions of classes and their packages should provide unambiguous information on where functionality can be found. Helpers for platform classes can be found in packages of the same name but prefixed with com.jakewharton.rxbinding.instead of android. and classes of the same name but prefixed with Rx. For example, android.widget.TextView bindings are in com.jakewharton.rxbinding.widget.RxTextView.

Observable factory method names is the plural of the verb (e.g., click → clicks()). The verb should be in the present tense, regardless of the platform's use (e.g., selected -> selection). When there are multiple versions of the same verb, prefix with a qualifying noun or adjective that differentiates (e.g., click vs. long click, item selection vs. nothing selection).

If the listener callback provides more than one parameter of useful data, a factory method overload named in the singular and suffixed with “Events” is included. This overload emits wrapper objects containing all the additional information about the event. The name of the wrapper object is the concatenation of the view simple name, the verb (with optional adverb prefix), and “Event”. These classes are in the public API.

Events for listeners with multiple methods should share an abstract base class. The naming follows the same rules as a normal event class but without the qualifying prefix. The constructor should be package-private to prevent subclasses other than those defined for the listener methods. This class should be in the public API.

The name of the OnSubscribe class for each observable is the concatenation of the view simple name, the verb (with optional prefix), and "OnSubscribe". These classes not in the public API.

Action factory method names are the same as the property (e.g., enabled). If the associated listener has a return value, an overload that accepts a Func1<E, T> named "handled" will be present for determining that value. No error handling will be done. These classes are not in the public API and are currently defined anonymously.

Also, read this article to implement Rxbinding your application.

Don’t waste your in handling callback hell.Someone said

Clocks slay timetime is dead as long as it is being clicked off by little wheels; only when the clock stops does time come to life.

Support Me on Ko-fi

PS: Clap for me to support me for the further articles. and bookmark it so that you can find the link for further parts.

Nitin Khanna

Written by

Founder and CEO of @nextstepcalling, Software Engineer, Entrepreneur, Poet

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade