Skip to content

Instantly share code, notes, and snippets.

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