0

I am trying to perform a cleanup after the subscriber has stopped listening to the publisher.

My approach was to register for a closing and deallocation event, but I am struggling to figure out when a subscriber has stopped listening for events coming from a PassthroughSubject.

By "subscriber has stopped listening", I mean that the subscriber (.sink, for example), which created the subscription, either deallocated the subscription or explicitly called cancel on the returned cancellable value.

I know other reactive libraries usually come with an onEnd operator, but Combine doesn't have it. Is that even the right pattern here?

maticzav
  • 880
  • 9
  • 17
  • 1
    What is the actual problem you are trying to solve here? This seems like an [XY problem](https://xyproblem.info). – Dávid Pásztor May 19 '22 at 08:28
  • @DávidPásztor I see what you mean and slightly modified the question, but I don't think it makes a significant difference. – maticzav May 19 '22 at 09:00
  • `handleEvents`? https://github.com/CombineCommunity/rxswift-to-combine-cheatsheet – Cy-4AH May 19 '22 at 09:10
  • 2
    I think what David Pasztor is suggesting is that if you have to care whether there is a subscriber, you're doing it wrong. A publisher is / should be lightweight. That's the whole point of publish and subscribe: the publisher signals, and "those who have ears to hear, let them hear". – matt May 19 '22 at 09:42
  • 1
    Adding to matt's comment: the hard lifting should be done by the subscription, not the publisher and the subscription is deallocated when it is cancelled, so using a custom `Subscription` is the ideal way of ensuring that any in progress work is cancelled/cleanup is done when your subscribers cancel their subscription. – Dávid Pásztor May 19 '22 at 10:31
  • @DávidPásztor could you clarify the dichotomy of publisher/subscription in subjects? I am specifically asking for subjects because the difference is clear with a "regular" publisher. – maticzav May 19 '22 at 10:47
  • @maticzav when using built-in Combine publishers (including subjects), the actual `Subscription` is hidden from you, since that's an implementation detail of the publisher, what kind of subscription it returns when it receives a subscriber. You should create a custom `Publisher` AND custom `Subscription` instead of using a `Subject` if there is heavy work involved, which requires cleanup after a subscription was cancelled. – Dávid Pásztor May 19 '22 at 11:24

0 Answers0