Search code examples
androidrx-javarx-java2rx-binding

Binding an RxJava Observable to a TextView's text property


Is there a way, perhaps using RxBinding, to bind an Observable<String> to a TextView object such that its .text property is kept up to date with the Observable? Obviously, you could subscribe() and manually update the text field, but a convenience method seems likely. I just can't find it, and the documentation hasn't yielded any answers for me.

A similar convenience method exists in RxSwift (or rather RxCocoa), in case that clarifies what I am asking for; it's called .bindTo() there.


Solution

  • Yes methods like this is presented in rx-binding library. For example for TextView RxTextView.text(textView) creates action which can be used as subscriber.

    See source code

    Usage would be something like this

    observable.subscribe(RxTextView.text(textView), Throwable::printStackTrace);
    

    Be careful with memory and read docs:

    Warning: The created observable keeps a strong reference to view. Unsubscribe to free this reference.

    It is not the same as bindTo magic but doing what you need.