Skip to content

Instantly share code, notes, and snippets.

@chrisbanes
Last active October 25, 2022 21:29
  • Star 36 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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()
}
}
}
@loki666
Copy link

loki666 commented Sep 14, 2018

private val scope: CoroutineScope = job + Dispatchers.Main
doesn't compile... it expect a CoroutineScope

@marenovakovic
Copy link

Yes, it doesn't compile, I have solved it like this:
protected val scope: CoroutineScope = CoroutineScope(Dispatchers.Main + job)

@iam1492
Copy link

iam1492 commented Nov 10, 2018

Great stuff!
Is it ok implement CoroutineScope from viewModel and just use launch instead of scope.launch?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment