Fix the leak model for a polling view model
Your task
An AI assistant wrote a SwiftUI view model that polls a feed with a repeating Timer, and the timer's closure captures self strongly. The run loop keeps the timer, the timer keeps its closure, and the closure keeps the view model, so every visit to the screen leaks one. Your team models the two possible fixes to see what survives a run of navigations.
An assistant wrote simulate_view_model_leak(lifecycle_events, weak_capture, invalidate_on_disappear), the model. It is in the editor. It has a bug. Find it and fix it.
Input and output:
lifecycle_events: the navigation log, in order.appearopens the screen, which creates a new view model and a new repeating timer.disappearcloses the most recently opened screen that is still open.weak_capture: the timer's closure capturesselfweakly, with[weak self].invalidate_on_disappear: closing a screen callsinvalidate()on its timer.- Return a list of two numbers: the view models still alive, then the timers still scheduled.
Rules the tests check:
- Ignore any other event, and ignore
disappearwhen no screen is open. - When a screen closes and
invalidate_on_disappearis true, its timer stops and its view model is freed. - When a screen closes,
invalidate_on_disappearis false andweak_captureis true, its view model is freed, but its timer stays scheduled and keeps firing. - When a screen closes and both are false, nothing is freed.
- Nothing else frees a view model or stops a timer.
Examples
simulate_view_model_leak(lifecycle_events: list[str], weak_capture: bool, invalidate_on_disappear: bool) -> list[int]Example 1
Input
simulate_view_model_leak(["appear", "disappear", "appear", "disappear", "appear", "disappear"], False, False)Output
[3, 3]Example 2
Input
simulate_view_model_leak(["appear", "disappear", "appear", "disappear", "appear", "disappear"], False, True)Output
[0, 0]