-
-
Save XinyueZ/0597a0ee1401e681eb3b511b691878a8 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
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() | |
} | |
} | |
} |
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(), 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