how to get last value in a Stream<String> using rxdart?

Salma. picture Salma. · Feb 2, 2019 · Viewed 8.1k times · Source

I have a stream that holds string values and i want to get the last value in that string. what's the best way to do it?

  Stream<String> get searchTextStream {
    return _searchController.stream.transform(
      StreamTransformer<String, String>.fromHandlers(
        handleData: (value, sink) {
          if (value.isEmpty || value.length < 4) {
            sink.addError('please enter some text..');
          } else {
            sink.add(value);
          }
        },
      ),
    );
  }

Answer

flamel2p picture flamel2p · Mar 23, 2019

Get the rxDart package from here https://pub.dartlang.org/packages/rxdart.

import 'package:rxdart/rxdart.dart'; // 1. Import rxDart package.
final _searchController = BehaviorSubject<String>();  // 2. Initiate _searchController as BehaviorSubject in stead of StreamController.

String _lastValue = _searchController.value; // 3. Get the last value in the Stream.

BehaviorSubject is an Object rxDart package. It works like a StreamController, by default the broadcast() is on and BehaviorSubject has more function than StreamController.