The RxBinding library

The RxBinding library provides a reactive application programming interface. Let's imagine that we want to observe an input of EditText and display this text in TextView.

The RxBinding library provides extension functions for user interface components, such as textChanges:

fun TextView.textChanges(): InitialValueObservable<CharSequence> {
return TextViewTextChangesObservable(this)
}

We can implement our example by using the textChanges function, as follows:

class RxActivity : AppCompatActivity() {

private val editText by lazy(LazyThreadSafetyMode.NONE) {
findViewById<EditText>(R.id.editText)
}

private val textView by lazy(LazyThreadSafetyMode.NONE) {
findViewById<TextView>(R.id.textView)
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rx)
editText
.textChanges()
.subscribe { textView.text = it }

}
}

In the preceding snippet, we invoked the textChanges function and subscribed to a retrieved subscriber. The textChanges method returns an instance of the Observable class that emits the text from the input. 

The result looks as follows, and shows that the text from the input immediately appears on the screen:


The RxBinding library also contains the clicks extension function, which looks as follows:

fun View.clicks(): Observable<Unit> {
return ViewClickObservable(this)
}

The clicks extension function returns an instance of the ViewClickObservable class.

Furthermore, the ViewClickObservable looks as follows:

private class ViewClickObservable(
private val view: View
) : Observable<Unit>() {

override fun subscribeActual(observer: Observer<in Unit>) {
if (!checkMainThread(observer)) {
return
}
val observer = Observer(view, observer)
observer.onSubscribe(observer)
view.setOnClickListener(observer)
}
}

It uses the subscribeActual method to pass an instance of the Observer class to the setOnClickListener of an instance of the View class.
The ViewClickObservable class inherits from the Observable class and overrides the subscribeActual method.
Finally, the Observer class looks as follows:

 private class Observer(
private val view: View,
private val observer: Observer<in Unit>
) : MainThreadDisposable(), OnClickObserver {

override fun onClick(v: View) {
if (!isDisposed) {
observer.onNext(Unit)
}
}

override fun onDispose() {
view.setOnClickListerner(null)
}
}

The preceding snippet invokes the onNext method when the onClick method is invoked.

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

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