DevPrep

All topics › Combine

How do you manage subscription memory (AnyCancellable)?

Middle PRO

The essence

sink and assign(to:on:) return an AnyCancellable — the subscription token. While it is alive the subscription is active; on its deinit (or an explicit cancel()) the subscription is cancelled and resources are freed. Hence two rules: keep the token (or the subscription dies immediately) and tie its lifetime to the owner — usually via store(in: &bag) into a Set<AnyCancellable> on the object that cares about the data.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store