Skip to content

Instantly share code, notes, and snippets.

@finnkvan
Created January 12, 2019 10:59
Show Gist options
  • Save finnkvan/80bdf350f1627ee782e3c2c5c10d8f9b to your computer and use it in GitHub Desktop.
Save finnkvan/80bdf350f1627ee782e3c2c5c10d8f9b to your computer and use it in GitHub Desktop.
// Copyright: https://developer.android.com/topic/libraries/architecture/livedata
class NameViewModel : ViewModel() {
// Create a LiveData with a String
val currentName: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
// Rest of the ViewModel...
}
class NameActivity : AppCompatActivity() {
private lateinit var mModel: NameViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Other code to setup the activity...
// Get the ViewModel.
mModel = ViewModelProviders.of(this).get(NameViewModel::class.java)
// Create the observer which updates the UI.
val nameObserver = Observer<String> { newName ->
// Update the UI, in this case, a TextView.
mNameTextView.text = newName
}
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
mModel.currentName.observe(this, nameObserver)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment