🎯

Stream distinct method

に公開

Distinct Stream Example

https://api.dart.dev/dart-async/Stream/distinct.html

概要

このサンプルでは、DartのStreamdistinct()メソッドの使用方法を説明します。distinct()は連続して重複する値をフィルタリングする機能を提供します。

公式のサンプル:

final stream = Stream.fromIterable([2, 6, 6, 8, 12, 8, 8, 2]).distinct();
stream.forEach(print); // Outputs events: 2,6,8,12,8,2.

コードの説明

Stream生成部分

Stream<int> distinctSleepStream() async* {
  var count = 0;
  final random = Random();
  
  while (count < 10) {
    final value = random.nextInt(3);  // 0, 1, 2 のいずれかの値
    yield value;
    await Future<void>.delayed(Duration(seconds: 1));
    count++;
  }
}
  • Random()を使用して0から2までのランダムな値を生成
  • 1秒ごとに値を出力
  • 合計10回の値を生成

distinct()の動作

final stream = distinctSleepStream().distinct();

distinct()メソッドは以下のように動作します:

  1. ストリームから値を受け取る
  2. 直前の値と比較
  3. 直前の値と同じ場合はスキップ
  4. 異なる値の場合のみ出力

出力例

オリジナル:

distinct()適用後:

ポイント

  • distinct()連続する重複のみを除去
  • 離れた位置にある同じ値は除去されない
  • 値の比較には==演算子が使用される
  • カスタムの比較関数も指定可能: distinct((previous, next) => /* カスタム比較 */)

使用例

  • 連続して発生する重複イベントの除去
  • センサーデータからのノイズ除去
  • ユーザー入力の重複防止

注意点

  • メモリ効率: distinct()は直前の値のみを保持
  • パフォーマンス: 比較関数が複雑な場合は処理時間に影響する可能性あり

Discussion