Observable(LiveData/Rx) Bind Extensions

Often times I find myself observing simple values from LiveData or Rx observables and setting them to view items like TextViews or EditTexts. Or setting visibility of a Button or TextView.

Post values in ViewModel
Observe values in MainActivity

Well, it looks ugly to me. We can do it more readable. RxSwift has bind() function to simply do this operation.

It binds ViewModel value to Label or Image Field

In order to achieve something similar, we can use Extension functions. So I created a file that called ReactiveBindExtensions in our project.

Here are some of the functions

With the help of these extension functions, we can convert our bindings into much readable and clean version. Even cleaner than RxSwift bind() function 🙂

Makes binding much readable

You can find the sample extension code in this gist.

import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import com.jakewharton.rxrelay2.BehaviorRelay
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
fun <T> LiveData<T>.bindText(lifecycleOwner: LifecycleOwner, textView: TextView?) {
this.observe(lifecycleOwner, Observer { textView?.text = it.toString() })
}
fun LiveData<Bitmap>.bindBitmap(lifecycleOwner: LifecycleOwner, imageView: ImageView?) {
this.observe(lifecycleOwner, Observer { imageView?.setImageBitmap(it) })
}
fun LiveData<Drawable>.bindDrawable(lifecycleOwner: LifecycleOwner, imageView: ImageView?) {
this.observe(lifecycleOwner, Observer { imageView?.setImageDrawable(value) })
}
fun LiveData<Boolean>.bindVisibility(lifecycleOwner: LifecycleOwner, view: View?) {
this.observe(
lifecycleOwner,
Observer { value ->
view?.visibility = if (value) View.VISIBLE else View.GONE
})
}
fun <T> BehaviorRelay<T>.bindText(textView: TextView?, bag: CompositeDisposable) {
this.subscribe { textView?.text = it.toString() }?.addTo(bag)
}
fun BehaviorRelay<Boolean>.bindVisibility(view: View?, bag: CompositeDisposable) {
this.subscribe { view?.isSelected = it }?.addTo(bag)
}

Originally posted on https://medium.com/@uludagcan/observable-livedata-rx-bind-extensions-4f2188a53ad1
Thanks for reading ❤️


Ask me on TwitterInstagram or Linkedin

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: