Skip to content

Instantly share code, notes, and snippets.

@chrisbanes
Last active March 20, 2025 17:42
Show Gist options
  • Select an option

  • Save chrisbanes/a9453de76c1e7dc54573a6e5bb765545 to your computer and use it in GitHub Desktop.

Select an option

Save chrisbanes/a9453de76c1e7dc54573a6e5bb765545 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()
}
}
}
@XinyueZ

XinyueZ commented Sep 13, 2018

Copy link
Copy Markdown

launch // no launch(ui){...} ?

@aouerf

aouerf commented Sep 13, 2018

Copy link
Copy Markdown

@XinyueZ UI is deprecated in favour of Dispatchers.Main. And since he set that as the coroutine context for theViewModel, launch uses that by default.

That being said, I prefer the default dispatcher to be Dispatchers.Default and switch to the main (or IO, but this shouldn't be necessary with the experimental scheduler) context when necessary.

@XinyueZ

XinyueZ commented Sep 13, 2018

Copy link
Copy Markdown

I C, got it, I have converted my project from experimental to non-experimental and I have seen a lot different things.

@XinyueZ

XinyueZ commented Sep 13, 2018

Copy link
Copy Markdown

I prefer

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

@loki666

loki666 commented Sep 14, 2018

Copy link
Copy Markdown

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

@marenovakovic

Copy link
Copy Markdown

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

@iam1492

iam1492 commented Nov 10, 2018

Copy link
Copy Markdown

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