Created
December 28, 2019 06:08
-
-
Save lagoJin/63cebf0447557707f4c7166400db52a2 to your computer and use it in GitHub Desktop.
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
private const val JOB_KEY = "androidx.lifecycle.ViewModelCoroutineScope.JOB_KEY" | |
/** | |
* [CoroutineScope] tied to this [ViewModel]. | |
* This scope will be canceled when ViewModel will be cleared, i.e [ViewModel.onCleared] is called | |
* | |
* This scope is bound to [Dispatchers.Main] | |
*/ | |
val ViewModel.viewModelScope: CoroutineScope | |
get() { | |
val scope: CoroutineScope? = this.getTag(JOB_KEY) | |
if (scope != null) { | |
return scope | |
} | |
return setTagIfAbsent(JOB_KEY, | |
CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main)) | |
} | |
internal class CloseableCoroutineScope(context: CoroutineContext) : Closeable, CoroutineScope { | |
override val coroutineContext: CoroutineContext = context | |
override fun close() { | |
coroutineContext.cancel() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment