Created
June 23, 2021 05:06
-
-
Save chao2zhang/a980118c2de110cebc3f13c867998fe2 to your computer and use it in GitHub Desktop.
Cancellation
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
@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