Created
January 12, 2019 10:59
-
-
Save finnkvan/80bdf350f1627ee782e3c2c5c10d8f9b to your computer and use it in GitHub Desktop.
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
// 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