Ruairi McGuigan, the MyViewModel
below has no reference to view, Lifecycle
, or any class that may hold a reference to the activity context.
class MyViewModel(private var count: Int = 0) : ViewModel(),
LifecycleObserver {
companion object { const val COUNT_KEY = "CountKey" }
val changeNotifier = MutableLiveData<Int>()
fun increment() { changeNotifier.value = ++count }
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() { increment() }
fun saveState(outState: Bundle) {
outState.putInt(COUNT_KEY, count)
}
fun restoreState(inState: Bundle?) {
inState?.let { count = inState.getInt(COUNT_KEY) }
}
}
Let me know if you find otherwise that I might have missed.