13

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);
          }
        },
      ),
    );
  }
Salma
  • 1,211
  • 2
  • 16
  • 33
  • 2
    You are probably looking for a `BehaviourSubject`. https://pub.dartlang.org/documentation/rxdart/latest/rx/BehaviorSubject-class.html – Philip Feldmann Feb 02 '19 at 10:15

2 Answers2

20

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.

flamel2p
  • 319
  • 1
  • 7
  • 1
    If someone runs into the same issue: There seemed to be a breaking change in the rxdart package where you can not use .value directly on a BehaviorSubject anymore. You would have to use "_searchController.valueWrapper.value" – kk_ Apr 03 '21 at 09:53
  • this is wrong code. _searchController.value return Future instead of a – Konstantin Voronov Dec 23 '22 at 15:58
0
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.first.then((value){_lastValue = value; });

rxDart is uses asynchronous approach. so there is now synchronous way to get it. Method First makes a auto canceling subscription and execute callback function when value is ready.