Consider a scenario where we have a stream emitting strings, and we want to save strings in files.
I am using PublishSubject and this works fine:
Subject<String> stream = PublishSubject.create();
stream.subscribe(str -> saveFile(str));
mReverseGeocoderStream.onNext("some-string1")
mReverseGeocoderStream.onNext("some-string2")
However, this doesn't work (only some-string2 gets delivered)
Subject<String> stream = PublishSubject.create();
mReverseGeocoderStream.onNext("some-string1")
stream.subscribe(str -> saveFile(str));
mReverseGeocoderStream.onNext("some-string2")
Is there a way to make the second scenario work as well?
i.e., Can we change PublishSubject to make sure it buffers the events until a subscriber consumes them?
Note that BehaviorSubject is not an option because re-subscribing causes another file save. It doesn't have the concept of "consuming events".
I found UnicastSubject which is pretty much what I want, except, it fails with IllegalStateException when I unsubscribe and later re-subscribe with a different subscriber.
Use case:
Assume we have an android app. It makes a network request, at the back of the network request, it needs to show a dialog. While the request is being made, the user backgrounds the app. At this point, we unsubscribe our observers that are listening for the signal to show the dialog.
Network request comes back and signal to show the dialog gets fired to the stream. No one is listening at this point. User foregrounds the app. A new subscriber gets attached to the network request manager (ViewModel). At this point, I'd like the "unconsumed" signal to get delivered to the subscriber.
Note: I cannot use the behavior subject. If I do that, every time user backgrounds and foregrounds the app the dialog will show up. I want the event to be consumed and finished once the dialog is shown.