Class Scope
java.lang.Object
megalodonte.base.async.Scope
Cancellation binding between async work (
Async.Run(RunnableThrowing)) and the lifecycle of
whoever initiated it (a screen, a ViewModel). Solves the same class of race that
viewModelScope/DisposableEffect solve in Jetpack Compose: cancelling is
synchronous and cheap (a flag), but the work itself only knows it was cancelled when it
checks — hence run(RunnableThrowing) and onCancel(Runnable) exist, instead of trying to force-interrupt.
One instance covers a single lifecycle (a screen, a ViewModel) and is not reusable after being cancelled.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidcancel()Cancels the scope:isCancelled()starts returningtrueand all callbacks registered viaonCancel(Runnable)run now, on the same thread (synchronous, just likeonDestroy()— cancelling is cheap, the actual cleanup work is each callback's responsibility).booleanvoidRegisterscleanupto run when the scope is cancelled.voidrun(RunnableThrowing task) Runstaskon a virtual thread, but only if the scope hasn't been cancelled at the moment the task begins executing.
-
Constructor Details
-
Scope
public Scope()
-
-
Method Details
-
run
Runstaskon a virtual thread, but only if the scope hasn't been cancelled at the moment the task begins executing. Ifcancel()has already run before that,taskis never called.This closes the race "onDestroy runs before Async.Run starts" — but not on its own the race "onDestroy runs in the middle of task", which still depends on
taskcheckingisCancelled()at the right points (e.g. right before opening a resource) or registering cleanup viaonCancel(Runnable). -
onCancel
Registerscleanupto run when the scope is cancelled. If already cancelled at the time of the call, runscleanupimmediately on the calling thread — covers the case where the resource finished being acquired aftercancel()already ran (e.g. connection that finished opening after the screen was already destroyed). -
cancel
public void cancel()Cancels the scope:isCancelled()starts returningtrueand all callbacks registered viaonCancel(Runnable)run now, on the same thread (synchronous, just likeonDestroy()— cancelling is cheap, the actual cleanup work is each callback's responsibility). -
isCancelled
public boolean isCancelled()
-