RxDart BehaviorSubject confusion


I have been using RxDart along my Flutter projects for a while. However I find it confusing that defining a BehaviorSubject you can listen directly to the subject, and also to the subject’s stream. I wasn’t really able to point out the difference.


BehaviorSubject<String> _mySubject = BehaviorSubject();

_mySubject.listen((value) => { print('Logging $value'} );
_mySubject.stream.listen((value) => { print('Logging $value'} );

Furthermore, BehaviorSubjects seem to offer two ways to access the last emitted value, from the docs I see the value getter which is synchronous. As well as the last getter returning a Future.

Once again I am confused. If nothing was emitted, then why isn’t the value getter returning null? Instead, it just waits. The only workaround I found was to seed the subject with a null value.

Finally, I tried using the last getter as a Future and it never returns. Wether there is data or not. Calling it on the Subject just never seems to work.


Thanks @pskink for pointing out that the stream getter returns the Subject itself, therefore no difference between my two first examples.


value should return null if nothing has been emitted yet, not sure why it didn’t work for you. Which version of RxDart are you using?

last on the other hand works a bit different. It will return the last value of a Stream after the Stream has been closed. So you need to call _mySubject.close(); then the Future will be completed (as long as the Stream has emitted any value, otherwise there will be an error).

Answered By – Josh

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *