Skip to content

Instantly share code, notes, and snippets.

@XinyueZ
Forked from chrisbanes/ScopedViewModel.kt
Created September 13, 2018 07:44
Show Gist options
  • Save XinyueZ/0597a0ee1401e681eb3b511b691878a8 to your computer and use it in GitHub Desktop.
Save XinyueZ/0597a0ee1401e681eb3b511b691878a8 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