Skip to content

Instantly share code, notes, and snippets.

@chao2zhang
Created June 23, 2021 05:06
Show Gist options
  • Save chao2zhang/a980118c2de110cebc3f13c867998fe2 to your computer and use it in GitHub Desktop.
Save chao2zhang/a980118c2de110cebc3f13c867998fe2 to your computer and use it in GitHub Desktop.
Cancellation
@MainThread
fun cancel() {
if (cancellationJob != null) {
error("Cancel call cannot happen without a maybeRun")
}
cancellationJob = scope.launch(Dispatchers.Main.immediate) {
delay(timeoutInMs)
if (!liveData.hasActiveObservers()) {
// one last check on active observers to avoid any race condition between starting
// a running coroutine and cancelation
runningJob?.cancel()
runningJob = null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment