Skip to content

Instantly share code, notes, and snippets.

@HarryTylenol
Last active June 19, 2018 00:29
Show Gist options
  • Save HarryTylenol/67265d8642b2d8860cd095a8e1084d9d to your computer and use it in GitHub Desktop.
Save HarryTylenol/67265d8642b2d8860cd095a8e1084d9d to your computer and use it in GitHub Desktop.
Anko LiveData Binding
class LifecycleGetter<T : View>(var lifecycleOwner: LifecycleOwner, var view: T)
fun <T : View> T.observe(lifecycleOwner: LifecycleOwner): LifecycleGetter<T> {
return LifecycleGetter(lifecycleOwner, this)
}
fun <T : TextView> LifecycleGetter<T>.liveText(liveData: LiveData<String>): LifecycleGetter<T> {
liveData.observe(lifecycleOwner, Observer {
this.view.text = it
})
return this
}
fun <T : View, X> LifecycleGetter<T>.liveVisibility(liveData: LiveData<X>, isVisibleAtNull: Boolean = false): LifecycleGetter<T> {
liveData.observe(lifecycleOwner, Observer {
if (isVisibleAtNull) this.view.isVisible = it == null
else this.view.isVisible = it != null
})
return this
}
fun <T : ImageView> LifecycleGetter<T>.liveUrlImage(liveData: LiveData<String>): LifecycleGetter<T> {
liveData.observe(lifecycleOwner, Observer {
Glide.with(this.view)
.load(it)
.apply(RequestOptions.circleCropTransform())
.into(this.view)
})
return this
}
fun <T : View> LifecycleGetter<T>.bind(): T {
return this.view
}
data class User(var name : String, var profileImage : String)
val lifecycleOwner = //.. can be Activity, Fragment or Something
val _userLiveData = MutableLiveData<User>()
val userLiveData : LiveData<User>() get() = _userLiveData
fun <T, R> LiveData<T>.map(f: (T) -> R): LiveData<R> = Transformations.map(this, f)
// Layout will visible when User from userLiveData is not null. (liveVisibility)
// if userLiveData is not null, automatically observe data,
// and provide profileImage to imageView (In my case, Glide), set user name to textView.
// Observer lifecycle depends on observe(LifecycleOwner)
verticalLayout {
imageView()
.observe(lifecycleOwner) // LifecycleGetter Scope
.liveUrlImage(userLiveData.map { it.profileImage })
.bind() // return ImageView
.lparams(dip(56), dip(56)) { bottomMargin = dip(24) }
textView()
.observe(lifecycleOwner) // LifecycleGetter Scope
.liveText(userLiveData.map { it.name })
.bind() // return TextViewView
.lparams(matchParent)
}.observe(lifecycleOwner).liveVisibility(userLiveData).bind()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment