Class Scope

java.lang.Object
megalodonte.base.async.Scope

public final class Scope extends Object
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
    Constructor
    Description
     
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    Cancels the scope: isCancelled() starts returning true and all callbacks registered via onCancel(Runnable) run now, on the same thread (synchronous, just like onDestroy() — cancelling is cheap, the actual cleanup work is each callback's responsibility).
    boolean
     
    void
    onCancel(Runnable cleanup)
    Registers cleanup to run when the scope is cancelled.
    void
    Runs task on a virtual thread, but only if the scope hasn't been cancelled at the moment the task begins executing.

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • Scope

      public Scope()
  • Method Details

    • run

      public void run(RunnableThrowing task)
      Runs task on a virtual thread, but only if the scope hasn't been cancelled at the moment the task begins executing. If cancel() has already run before that, task is 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 task checking isCancelled() at the right points (e.g. right before opening a resource) or registering cleanup via onCancel(Runnable).

    • onCancel

      public void onCancel(Runnable cleanup)
      Registers cleanup to run when the scope is cancelled. If already cancelled at the time of the call, runs cleanup immediately on the calling thread — covers the case where the resource finished being acquired after cancel() already ran (e.g. connection that finished opening after the screen was already destroyed).
    • cancel

      public void cancel()
      Cancels the scope: isCancelled() starts returning true and all callbacks registered via onCancel(Runnable) run now, on the same thread (synchronous, just like onDestroy() — cancelling is cheap, the actual cleanup work is each callback's responsibility).
    • isCancelled

      public boolean isCancelled()