LogoSignals.dart
Copy Markdown
rodydavis/signals.dart 999999

SignalContainer

Signal container used to create signals based on args.

Signal container used to create signals based on args

final container = readonlySignalContainer<Cache, String>((e) {
  return signal(Cache(e));
});

final cacheA = container('cache-a');
final cacheB = container('cache-b');
final cacheC = container('cache-c');

Example of settings and SharedPreferences:

class Settings {
  final SharedPreferences prefs;
  EffectCleanup? _cleanup;

  Settings(this.prefs) {
    _cleanup = effect(() {
      for (final entry in setting.store.entries) {
        final value = entry.value.peek();
        if (prefs.getString(entry.key.$1) != value) {
          prefs.setString(entry.key.$1, value).ignore();
        }
      }
    });
  }

  late final setting = signalContainer<String, (String, String)>(
    (val) => signal(prefs.getString(val.$1) ?? val.$2),
    cache: true,
  );

  Signal<String> get darkMode => setting(('dark-mode', 'false'));

  void dispose() {
    _cleanup?.call();
    setting.dispose();
  }
}

void main() {
 // Load or find instance
 late final SharedPreferences prefs = ...;

 // Create settings
 final settings = Settings(prefs);

 // Get value
 print('dark mode: ${settings.darkMode}');

 // Update value
 settings.darkMode.value = 'true';
}

Constructors#

View Constructors
SignalContainer(this._create, {this.cache = false, this.onEvict})

Signal container used to create multiple signals via args

Properties#

View Properties
bool cache

If true then signals will be cached when created

void Function(Arg key, S signal)? onEvict

Optional callback when a signal is removed/evicted from the cache

store

Store of created signals (if cache is true)

Methods#

View Methods
S call(Arg arg)

Create the signal with the given args

S? remove(Arg arg)

Remove a signal from the cache

bool containsKey(Arg arg)

Check if signal is currently stored in the cache

void clear()

Clear the cache

void dispose()

Dispose of all created signals

int length

Returns the number of cached signals.

bool isEmpty

Returns true if the cache is empty.

bool isNotEmpty

Returns true if the cache is not empty.

Iterable<Arg> keys

Returns all currently cached keys.

Iterable<S> values

Returns all currently cached signals.

Iterable<MapEntry<Arg, S>> entries

Returns all currently cached entries.

S? lookup(Arg arg)

Retrieve the cached signal for arg if it exists, without creating a new one if it is missing.

void removeWhere(bool Function(Arg key, S signal) test)

Filter and remove matching cached signals.


signalContainer#

Create a signal container used to instance signals based on args

final container = signalContainer<Cache, String>((e) {
  return signal(Cache(e));
});

final cacheA = container('cache-a');
final cacheB = container('cache-b');
final cacheC = container('cache-c');

cacheA.value = 'a';
cacheB.value = 'b';
cacheC.value = 'c';