Save last emitted value of stream in Dart
Asked Answered
A

5

6

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?

Agueda answered 20/12, 2018 at 14:23 Comment(0)
T
8

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.

Tooling answered 20/12, 2018 at 22:40 Comment(0)
C
7

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.

Calcaneus answered 22/11, 2020 at 12:4 Comment(0)
C
5

Convert stream to BehaviorSubject in rxDart.

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

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

Cartilage answered 5/12, 2019 at 7:55 Comment(0)
A
1

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

Agueda answered 21/12, 2018 at 22:29 Comment(1)
Which may mean you have a race condition in production on slower or differently configured devices?Eurasian
A
0

You could have a look at BehaviorSubject in rxdart. According to the docs

The latest item that has been added to the subject will be sent to any new listeners of the subject.

Argentine answered 20/12, 2018 at 15:37 Comment(4)
Thanks, but how do I convert a dart stream to a behaviorsubject?Pettit
BehaviorSubject implements ValueObservable which implements Observable which extends Stream. BehaviorSubject can do everything a stream can do plus more so it should just be a straight replacement.Argentine
Sure, but the firestore plugin returns a dart stream, how can I use it to make a behaviorsubject?Pettit
@SondreSørbye have you found out how to convert a dart stream to behaviorsubject?Hooded

© 2022 - 2024 — McMap. All rights reserved.