Skip to content

Instantly share code, notes, and snippets.

@tizisdeepan
Last active July 29, 2020 14:14
Show Gist options
  • Save tizisdeepan/fc24bf774ada080eb17d2ad4a4ab0c1a to your computer and use it in GitHub Desktop.
Save tizisdeepan/fc24bf774ada080eb17d2ad4a4ab0c1a to your computer and use it in GitHub Desktop.
MVVM with LiveData
onCreate() {
val viewModel = ... //initialize your view model
viewModel.getData()
viewModel.data.observe(this, Observer {
//do operations based on the value
})
}
private var parentJob = Job()
private val coroutineContext: CoroutineContext
get() = parentJob + Dispatchers.IO
private val scope = CoroutineScope(coroutineContext)
val data: LiveData<Data> = MutableLiveData()
fun getData() {
scope.launch {
//do network calls
override onSuccess(data: Data) {
data.value = data
}
}
}
val data: LiveData<Data> = MutableLiveData()
fun getData() {
data = repository.getData()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment