-
-
Save albodelu/23a340537a46c3b4fafdb385fe7a7066 to your computer and use it in GitHub Desktop.
Databinding
This file contains hidden or 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
//primera opción extener una funcin sobre [BaseObservable] que emita una [ObservableProperty] que emite el cambio y lo notifica | |
// a los databinders para repintar | |
inline fun <Param> BaseObservable.bindingParam(initialValue: Param, | |
crossinline afterChange: (Param) -> Unit): ReadWriteProperty<BaseObservable, Param> = | |
object : ObservableProperty<Param>(initialValue) { | |
override fun afterChange(property: KProperty<*>, oldValue: Param, newValue: Param) { | |
if (oldValue != newValue) { | |
[email protected]() | |
afterChange(newValue) | |
} | |
} | |
} | |
//la otra opción es crear una extensión sobre ObservableField para que emita un Observable de Rx al que nos | |
//podamos suscribir. | |
private inline fun <reified T : DataBindingObservable, R : Any?> T.observe( | |
crossinline block: (T) -> R | |
): Observable<R> = create { subscriber -> | |
object : android.databinding.Observable.OnPropertyChangedCallback() { | |
override fun onPropertyChanged(observable: DataBindingObservable, id: Int) = try { | |
subscriber.onNext(block(observable as T)) | |
} catch (e: Exception) { | |
subscriber.onError(e) | |
} | |
}.let { | |
subscriber.setCancellable { this.removeOnPropertyChangedCallback(it) } | |
this.addOnPropertyChangedCallback(it) | |
} | |
} |
This file contains hidden or 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
class ViewModel: BaseObservable { | |
val _name = ObservableField<String>("") | |
val _lastName = ObservableField<String>("") | |
var enabled: Boolean by bindingParam(false) {} | |
Observable.combineLatest(_name.observe(), | |
_lastName.observe(), | |
BiFunction { name: String, lastName: String -> | |
enabled = name.isNotBlank() && lastName.isNotBlank() | |
}) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment