Created
September 8, 2019 19:21
-
-
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.
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
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
Reference: