Skip to content

Instantly share code, notes, and snippets.

@Gamezpedia
Forked from chrisbanes/ScopedViewModel.kt
Created September 26, 2018 21:13
Show Gist options
  • Save Gamezpedia/1d080ef33a90ea926d7ea9f4db41772e to your computer and use it in GitHub Desktop.
Save Gamezpedia/1d080ef33a90ea926d7ea9f4db41772e to your computer and use it in GitHub Desktop.
ScopedViewModel
open class ScopedViewModel : ViewModel() {
private val job = Job()
protected val scope: CoroutineScope = job + Dispatchers.Main
override fun onCleared() {
super.onCleared()
job.cancel()
}
}
class DetailViewModel : ScopedViewModel() {
fun startTask() {
scope.launch {
// Switch the 'background' thread
withContext(Dispatchers.Default) {
// do your long-running thing
}
// We're now back on the Android's Main thread (since we're using
// the ScopedViewModel's scope)
updateUi()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment