Last active
October 2, 2024 04:13
-
-
Save chrisbanes/a9453de76c1e7dc54573a6e5bb765545 to your computer and use it in GitHub Desktop.
ScopedViewModel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open class ScopedViewModel : ViewModel() { | |
private val job = Job() | |
protected val scope: CoroutineScope = job + Dispatchers.Main | |
override fun onCleared() { | |
super.onCleared() | |
job.cancel() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} |
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
Yes, it doesn't compile, I have solved it like this:
protected val scope: CoroutineScope = CoroutineScope(Dispatchers.Main + job)