Fix the subscription model for a balance screen
Your task
An AI wrote a view controller that subscribes to a shared Combine publisher in viewDidLoad and updates a balance label. It throws away the AnyCancellable that sink returns, and it captures self strongly. After a few visits, closed screens were still updating and duplicate network requests multiplied. Your team models the two fixes to see what each one stops.
An assistant wrote audit_subscription_leak(navigation_events, store_cancellable, weak_self), the model. It is in the editor. It has a bug. Find it and fix it.
Input and output:
navigation_events: the log, in order.openshows a balance screen, which subscribes.closecloses the most recently opened screen that is still open.emitis one new value from the shared publisher.store_cancellable: each screen keeps itsAnyCancellableand cancels it when the screen closes.weak_self: thesinkclosure captures[weak self].- Return a list of two numbers: the upstream requests made, then the closed screens still held in memory.
Rules the tests check:
- Ignore any other event, and ignore
closewhen no screen is open. - Each
emitmakes one upstream request for every live subscription. - When a screen closes and
store_cancellableis true, its subscription ends. - When a screen closes and
store_cancellableis false, its subscription stays live and keeps making requests, whateverweak_selfis. - A closed screen whose subscription is still live is held in memory, unless
weak_selfis true.
Examples
audit_subscription_leak(navigation_events: list[str], store_cancellable: bool, weak_self: bool) -> list[int]Example 1
Input
audit_subscription_leak(["open", "emit", "close", "open", "emit", "close", "open", "emit"], False, False)Output
[6, 2]Example 2
Input
audit_subscription_leak(["open", "emit", "close", "open", "emit", "close", "open", "emit"], True, False)Output
[3, 0]Example 3
Input
audit_subscription_leak(["open", "emit", "close", "open", "emit", "close", "open", "emit"], False, True)Output
[6, 0]