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

2

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);
          }
        },
      ),
    );
  }
Humiliating answered 2/2, 2019 at 10:9 Comment(1)
You are probably looking for a BehaviourSubject. pub.dartlang.org/documentation/rxdart/latest/rx/…Congregation
G
21

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.

Gelinas answered 23/3, 2019 at 1:21 Comment(2)
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"Sickness
this is wrong code. _searchController.value return Future<String> instead of a <String>Transitory
T
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.

Transitory answered 23/12, 2022 at 16:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.