RaiiTimer class

A managed Timer that integrates with the RAII lifecycle system.

RaiiTimer wraps a standard Timer and provides automatic cancellation when its parent lifecycle is disposed. This prevents common issues like timers firing after their associated widget or component has been disposed.

The timer can be cancelled manually by calling cancel, or it will be automatically cancelled when the parent RaiiLifecycleAware is disposed.

Example usage:

class NotificationManager with RaiiLifecycleMixin {
  void scheduleNotification() {
    // Create timer using the extension method
    final timer = Timer(Duration(seconds: 5), () {
      showNotification('Your task is ready!');
    }).withLifecycle(this);

    // Can manually cancel if needed
    if (userCancelled) {
      timer.cancel();
    }

    // Can check timer state
    if (timer.isActive) {
      print('Timer is still running');
    }
  }

  void schedulePeriodicTask() {
    final timer = Timer.periodic(Duration(seconds: 1), (t) {
      print('Tick: ${t.tick}');
    }).withLifecycle(this);

    // Access the timer's tick count
    print('Current tick: ${timer.tick}');
  }
}

The timer follows this lifecycle:

  1. Created via RaiiTimer.withLifecycle (typically through TimerRaiiExt.withLifecycle)
  2. Registered with parent RaiiLifecycleAware
  3. Timer runs until completion, manual cancellation, or parent disposal
  4. On disposal: timer is cancelled, lifecycle is cleaned up, and unregistered from parent

See also:

Mixed-in types

Constructors

RaiiTimer.withLifecycle(RaiiLifecycleAware lifecycleAware, {required Timer timer, String? debugLabel})
Creates a new RaiiTimer and attaches it to the given lifecycleAware.

Properties

debugLabel String?
Optional label for debugging purposes.
final
hashCode int
The hash code for this object.
no setterinherited
isActive bool
Whether the timer is still active and waiting to fire.
no setter
isDisposed bool
Whether this lifecycle has been disposed.
no setterinherited
raiiHolder RaiiLifecycleAware?
The holder that manages this lifecycle.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
tick int
The number of times the timer has fired.
no setter

Methods

cancel() → void
Cancels the timer and disposes its lifecycle.
clearRaiiHolder() → void
Clears the holder reference.
inherited
disposeLifecycle() → void
Disposes of any resources held by this object.
override
initLifecycle() → void
Initializes the lifecycle of this object.
override
isLifecycleMounted() bool
Returns whether this object's lifecycle is currently mounted.
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
setRaiiHolder(RaiiLifecycleAware holder) → void
Sets the holder for this lifecycle.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited