val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java) } } • No more reference to Views. Ever • A factory can be used for more complex ViewModels • Created once and shared with multiple Fragments ViewModel How class MyActivity : AppCompatActivity() { public override fun onCreate() { val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java) } } class MyViewModel : ViewModel() { } class MyActivity : AppCompatActivity() { public override fun onCreate() { val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java) titleTextView.text = viewModel.title } } class MyViewModel : ViewModel() { val title = "Great title" } class MyActivity : AppCompatActivity() { public override fun onCreate() { val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java) titleTextView.text = viewModel.title redButton.onClick { viewModel.redButtonClicked() } } } class MyViewModel : ViewModel() { val title = "Great title" fun redButtonClicked() { ... } }
onPause, onStart, etc. LiveData We can’t push data from a ViewModel into an Activity or Fragment We need a data provider in our ViewModel so the View can subscribe to it Why & What LiveData is a lifecycle-aware observable that holds data and provides updates
not emitted to any Observer onStart() => LiveData value is emitted to all Observers on main thread onStop() => LiveData value is updated but not emitted to any Observer onDestroy() => LiveData stops being observed LiveData How
LiveData How class MyActivity : AppCompatActivity() { public override fun onCreate() { val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java) } } class MyViewModel : ViewModel() { val userName = MutableLiveData<String>() fun updateUserName(newUserName: String) { userName.value = newUserName // In main thread or userName.postValue(newUserName) // In background thread } } class MyActivity : AppCompatActivity() { public override fun onCreate() { val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java) viewModel.userName .observe(this, Observer { value -> updateUserTextView(value) }) } }