搜尋套件、儲存庫與 APP 分類

套件詳情v2.0.0

simple_observable

使用 Future、Stream 和/或回調觀察值的變更。

AndroidiOSWebmacOSWindowsLinux
近 30 天下載
19.9萬
喜歡數
6
Pub 分數
160

安裝套件

flutter pub add simple_observable

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

simple_observable 是一個輕量級的 Dart 套件,可透過 Futures、Streams 或回呼函數輕鬆觀察值的變更。它透過提供乾淨的介面來響應資料更新,從而簡化反應式程式設計,無需撰寫冗長的樣板程式碼。非常適合用於 Flutter 應用中的狀態管理,支援 Android、iOS、Web、macOS、Windows 及 Linux 等多個平台。此套件透過減少追蹤非同步資料流程的複雜性,提升開發者的工作效率。

適用情境

  • 即時資料更新
  • Flutter 應用中的狀態管理
  • 事件驅動的UI更新
  • 處理非同步資料流
  • 簡化回呼邏輯

主要特色

  • 支援 Futures 和 Streams
  • 基於回呼的觀察
  • 最小化樣板程式碼
  • 跨平台相容性
  • 與現有程式碼的輕鬆整合

適合對象

  • 尋求簡單狀態更新的開發者
  • 具有反應式 UI 的 Flutter 應用需要
  • 避免使用複雜狀態管理方案的專案
  • 重視程式碼簡潔性的團隊
  • 需要輕量級可觀測性的應用

使用建議

  • 不適合複雜的狀態樹
  • 限於基本觀察模式
  • 無內建的持久化或還原功能
  • 最適合中小型應用
  • 需要手動處理訂閱

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

pub.dev

simple_observable

Observe value changes using a Future, Stream, and/or a callback.

Source

class Observable<T> {
  Observable({T initialValue, this.onChanged, this.checkEquality = true})
      : _value = initialValue;

  /// If true, setting the [value] will only notifiy if the new value is different
  /// than the current value.
  final bool checkEquality;
  final void Function(T value) onChanged;

  var _completer = Completer<T>();

  bool _canceled = false;
  bool get canceled => _canceled;

  T _value;

  /// The current value of this observable.
  T get value => _value;
  set value(T val) {
    if (!canceled && (!checkEquality || _value != val)) {
      _value = val;
      // Delaying notify() allows the Future and Stream to update correctly.
      Future.delayed(Duration(microseconds: 1), () => notify(val));
    }
  }

  /// Alias for [value] setter. Good for passing to a Future or Stream.
  void setValue(T val) => value = val;

  @protected
  @mustCallSuper
  void notify(T val) {
    if (onChanged != null) onChanged(val);
    // Completing with a microtask allows a new completer to be constructed
    // before listeners of [nextValue] are called, allowing them to listen to
    // nextValue again if desired.
    _completer.complete(Future.microtask(() => val));
    _completer = Completer<T>();
  }

  Future<T> get nextValue => _completer.future;
  Stream<T> get values async* {
    while (!canceled) {
      yield await nextValue;
    }
  }

  /// Permanently disables this observable. Further changes to [value] will be
  /// ignored, the outputs [onChanged], [nextValue], and [values] will not be
  /// called again.
  @mustCallSuper
  void cancel() => _canceled = true;
}

所屬分類

依賴

依賴清單 1 項

原始碼儲存庫

使用此套件的專案