Skip to content

Instantly share code, notes, and snippets.

@IlyaGulya
Created February 28, 2019 04:59
Show Gist options
  • Save IlyaGulya/f4b5daead4ddfee9c776b6de154431f5 to your computer and use it in GitHub Desktop.
Save IlyaGulya/f4b5daead4ddfee9c776b6de154431f5 to your computer and use it in GitHub Desktop.
package ru.campuz.base
import android.databinding.Observable
import android.databinding.ObservableField
fun <T, R> ObservableField<T>.map(mapper: (T?) -> R): ObservableField<R> {
return MappedObservableField(this, mapper)
}
class MappedObservableField<T, R>(
val observableField: ObservableField<T>,
val mapper: (T?) -> R
) : ObservableField<R>() {
init {
observableField.get()?.let(mapper)
observableField.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
[email protected](observableField.get().let(mapper))
}
})
}
}
fun <T, V, R> combineLatest(o1: ObservableField<T>, o2: ObservableField<V>, mapper: (T?, V?) -> R): ObservableField<R> {
return CombineLatestObservableField(o1, o2, mapper)
}
fun <T, V, R> ObservableField<T>.combineWith(o2: ObservableField<V>, mapper: (T?, V?) -> R): ObservableField<R> {
return combineLatest(this, o2, mapper)
}
class CombineLatestObservableField<T, V, R>(
val o1: ObservableField<T>,
val o2: ObservableField<V>,
val mapper: (T?, V?) -> R
) : ObservableField<R>() {
var o1LastValue: T? = null
var o2LastValue: V? = null
init {
update(o1.get(), o2.get())
o1.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
update(o1.get(), o2LastValue)
}
})
o2.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
update(o1LastValue, o2.get())
}
})
}
private fun update(v1: T?, v2: V?) {
o1LastValue = v1
o2LastValue = v2
mapper(v1, v2)
}
}
val oRegistrationStatus = ObservableFieldProperty(RegistrationStatus.AVAILABLE)
val oParticipationStatus = ObservableFieldProperty(ParticipationStatus.NOT_PARTICIPATING)
val oParticipateButtonVisible = oParticipationStatus.map { it == ParticipationStatus.NOT_PARTICIPATING }
val oParticipateButtonActive = oRegistrationStatus.map { it == RegistrationStatus.AVAILABLE }
val oCancelParticipationButtonVisible = oParticipationStatus.map { it == ParticipationStatus.PARTICIPATING }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment