Last active
April 12, 2020 13:07
-
-
Save canuludag/d91c5cf40c631271767fc7f593ad663e to your computer and use it in GitHub Desktop.
Post about this Gist is on Medium: https://medium.com/@uludagcan/observable-livedata-rx-bind-extensions-4f2188a53ad1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment