Romain-Guillot
Romain-Guillot

Reputation: 31

Stream not updated in another stream listen function

I have two streams, I want to put data in the second stream when there are new data in the first one.

I have my class A, in the constructor I put the integer 1 in the stream a, and I listen this stream, when there are new data, I put the integer 4 in the stream b.

class A {
  Stream<int> a = BehaviorSubject<int>();
  Stream<int> b = BehaviorSubject<int>();

  A() {
    a = getDataA();

    a.listen((data) {
      b = getDataB();
    });
  }

  getDataA() {
    var _tmp = BehaviorSubject<int>();
    _tmp.add(1);
    return _tmp.stream;
  }

  getDataB() {
    var _tmp = BehaviorSubject<int>();
    _tmp.add(4);
    return _tmp.stream;
  }
}

And the widget that used the stream :

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return StreamBuilder(
      stream: objecta.b,
      builder: (BuildContext ctx, AsyncSnapshot<int> snap) {
        return Text((snap.data ?? -1).toString());
      },
    );
  }

The widget displays -1, instead of 4.

Upvotes: 0

Views: 507

Answers (1)

jbarat
jbarat

Reputation: 2460

You are not actually updating the stream but create a new one every time.

Do it this way instead:

class A {
  Stream<int> a = BehaviorSubject<int>();
  Stream<int> b = BehaviorSubject<int>();

  A() {
     a.listen((data) {
       b.sink.add(data);
     });
  }
}

Upvotes: 1

Related Questions