Fix the lifecycle replay for a profile load

Review the AI's codeMedium15 minGoogle style

Your task

An AI wrote an Android Fragment that loads a profile in GlobalScope and then sets binding.nameLabel.text. Testers who rotate the device or back out during the load see crashes: the job outlives the view, and the binding it holds is gone. Your team replays lifecycle logs to see what each finished job does to the screen.

An assistant wrote simulate_fragment_updates(event_lines, use_view_scope), the replay. It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • event_lines: the lifecycle log, in order. create is onViewCreated, which makes a new view with a new binding. destroy is onDestroyView. start:<id> launches a load job from the current view. complete:<id> means that job finished and touches the binding it held when it started.
  • use_view_scope: jobs run in viewLifecycleOwner.lifecycleScope instead of GlobalScope.
  • Return one outcome per complete, in order.

Rules the tests check:

  • Split a line at its first : into a verb and an argument. Skip start and complete lines with an empty argument, and skip any other verb.
  • Views are numbered. Before the first create, the current view is number 0 and is not alive. Each create makes the next number the current view, alive. destroy makes the current view not alive.
  • start:<id> ties the job to the current view number and clears any cancellation. Starting a known id again re-arms it the same way.
  • On destroy, when use_view_scope is true, every job tied to the current view number is cancelled.
  • complete:<id>:
    • never started: unknown:<id>
    • cancelled: cancelled:<id>
    • the current view is alive and is the view the job is tied to: updated:<id>
    • otherwise: crash:<id>
  • Completing a job does not remove it, so it can complete again.

Examples

simulate_fragment_updates(event_lines: list[str], use_view_scope: bool) -> list[str]
Example 1
Inputsimulate_fragment_updates(["create", "start:a", "complete:a"], False)
Output["updated:a"]
Example 2
Inputsimulate_fragment_updates(["create", "start:a", "destroy", "complete:a"], False)
Output["crash:a"]
Example 3
Inputsimulate_fragment_updates(["create", "start:a", "destroy", "complete:a"], True)
Output["cancelled:a"]