Daily iOS
Memory and ARC

Subscription lifetime

In a live coding session you're handed the following Combine ViewModel. Add a feature that subscribes to the price stream and reflects it in priceText, and explain, with code, how you'd handle unsubscribing.

final class ProductViewModel {
    @Published var priceText = ""
    private let priceStream: AnyPublisher<Decimal, Never>
    init(priceStream: AnyPublisher<Decimal, Never>) {
        self.priceStream = priceStream
    }
}
How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

Store the sink result in a Set<AnyCancellable> property. When the ViewModel is deallocated the cancellables deinit and the subscription cancels itself; if you keep it in a local variable, the subscription ends as soon as the function returns.

Share a question