Skip to content

Instantly share code, notes, and snippets.

@gabrielbmoro
Created September 8, 2019 19:21
Show Gist options
  • Save gabrielbmoro/b21f0c6eaf7e352cd89c3ef5cdef3d12 to your computer and use it in GitHub Desktop.
Save gabrielbmoro/b21f0c6eaf7e352cd89c3ef5cdef3d12 to your computer and use it in GitHub Desktop.
BaseViewModel is an abstraction used to do the ViewModel able to implement the Observable behavior.
import android.app.Application
import androidx.databinding.Bindable
import androidx.databinding.Observable
import androidx.databinding.PropertyChangeRegistry
import androidx.lifecycle.AndroidViewModel
open class BaseViewModel(application: Application) : AndroidViewModel(application), Observable {
@Transient
private var mCallbacks: PropertyChangeRegistry? = null
override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback) {
synchronized(this) {
if (mCallbacks == null) {
mCallbacks = PropertyChangeRegistry()
}
}
mCallbacks?.add(callback)
}
override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback) {
synchronized(this) {
if (mCallbacks == null) {
return
}
}
mCallbacks?.remove(callback)
}
/**
* Notifies listeners that a specific property has changed. The getter for the property
* that changes should be marked with [Bindable] to generate a field in
* `BR` to be used as `fieldId`.
*
* @param fieldId The generated BR id for the Bindable field.
*/
fun notifyPropertyChanged(fieldId: Int) {
synchronized(this) {
if (mCallbacks == null) {
return
}
}
mCallbacks?.notifyCallbacks(this, fieldId, null)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment