Save last emitted value of stream in Dart

5,265

Solution 1

Use the shareValue operator of rxdart:

final observable = Observable(yourStream).shareValue();

Internally, this operator uses a BehaviorSubject. It will subscribe to the stream as soon as there is a single subscriber (it will only subscribe once), and unsubscribe (and dispose the subject) when there are no more subscribers.

Also, as you said, you have to create the observable in initState or a similar method (NOT the build method!). The observable should be stored in a field in the State.

Solution 2

In the currently accepted answer, the Observable class in RXDart has now been deprecated. Instead, you could use a BehaviorSubject but its probably best to use a ValueConnectableStream instead, like this:

final newStream = ValueConnectableStream(yourStream).autoConnect()

See the RXDart docs for more info.

Solution 3

Convert stream to BehaviorSubject in rxDart.

BehaviorSubject<Data> _subject = BehaviorSubject<Data>();

stream.listen((x) => _subject.add(x));

Solution 4

I ran the flutter app in release mode and the lag was gone, without any modifications.

Share:
5,265
Sondre Sørbye
Author by

Sondre Sørbye

Updated on December 08, 2022

Comments

  • Sondre Sørbye
    Sondre Sørbye over 1 year

    I make an app using firestore and a bottom navigation bar in Flutter. The problem is that when I switch between tabs, the build method is called everytime. The build method downloads data from firestore. Therefore, the app flickers when I switch tabs (the spinning bar is showed for a very short time). I tried to fix this by moving the firestore stream to the constructor. However, since the stream can emit before the build method, it loads forever.

    A solution could been to save the last value that was emitted. I tried to fix this using the shareReplay method in Rx, but they have not implemented in RxDart yet. So, what is the best practice to implement this?