villb
villb

Reputation: 311

Combine: Cancel a Set<AnyCancellable> or remove all its stored objects to stop the subscriptions

If I have a Set of AnyCancellable:

var observations: Set<AnyCancellable> = []

What's the difference between removing all the objects from the set:

observations.removeAll()

or cancel each subscription:

observations.forEach { $0.cancel() }

do they have the same effect? or in case that there is a strong reference in any of the subscription if .removeAll() is called the strong references will be not eliminated? In case that they have the same effect I guess it will be a good practice to use the first approach as you don't need to traverse all the Set.

Upvotes: 5

Views: 3023

Answers (1)

jrturton
jrturton

Reputation: 119242

If there are strong references to any of the cancellables in the set, that implies that other parties are interested in them, and therefore they should not be cancelled explicitly.

By removing the reference, you're saying that the owner of observations is no longer interested in those cancellables. If that was the only owning reference, then cancel will happen automatically.

If you explicitly cancel each cancellable and you have other strong references by mistake, then you might be masking the effect of those mistakes, making them harder to find. If you have other strong references on purpose, you're going to have things being cancelled that you don't expect. So just empty the set.

Upvotes: 5

Related Questions