How best to release elements in a ReplaySubject?
See original GitHub issueHi,
We’re using ReplaySubject to keep a streamed response from a server into a buffer, in order to be able to pass the whole (finite) sequence to observables that subscribe to the subject.
The whole sequence may take a bit of time to complete, but we want to pass the Observable right away to client code.Furthermore, client code may not immediately subscribe to the flow, or it could subscribe several time to do multiple processing of the sequence.
Thus the use of ReplaySubject to avoid replaying the original request each time, and to avoid blocking for the server to respond with the whole sequence.
However, said elements are resources that are reference counted and should be manually freed before being garbage collected. What do you think is the best approach to cope with that?
Maybe what we need is to add semantics on the ReplaySubject to do cleanup and clear the buffer (like a dispose()
or release()
method)? This would probably also be needed in the bounded ReplaySubject to plug in cleanup behavior at eviction time…
Maybe there is a better alternative to ReplaySubject? Or a simple solution like foreaching on the items and cleaning them up this way?
I hope someone will be able to make a suggestion, and I’d be delighted to contribute if it makes sense 😉 Thanks!
Issue Analytics
- State:
- Created 9 years ago
- Comments:17 (17 by maintainers)
Using Subjects directly are almost never the desired solution as they don’t compose with backpressure or resource cleanup (unsubscription). Subjects are very imperative in use and “hot” in how data flows through them.
For example, using
cache()
internally usesReplaySubject
but it will be garbage collected once references to the Observables are released. Orreplay().refCount()
is even better, as once allSubscriber
s are done it willunsubscribe
up the chain and dispose of the underlyingReplaySubject
.Your use case however sounds like you should use
Observable.create
to represent your data source since then you can manage the cleanup as you need to (since you need to manage the reference counting).Thus, I suggest something like the following:
This outputs:
getValues()
right? awesome 😍