Skip to content

Run a child component's async callback against that child - #705

Open
cmcmanus96 wants to merge 1 commit into
NativePHP:mainfrom
cmcmanus96:live-child-async-receiver
Open

cmcmanus96 wants to merge 1 commit into
NativePHP:mainfrom
cmcmanus96:live-child-async-receiver

Conversation

@cmcmanus96

Copy link
Copy Markdown

A finished() or failed() closure written inside a child component runs against the screen instead of the child. So $this->result = $result sets a property on the screen, and the child that started the task never sees its result.

class CommitCard extends NativeComponent
{
    public ?array $preview = null;

    public function loadPreview(string $url): void
    {
        AsyncTask::dispatch(static fn () => Http::get($url)->json())
            ->finished(function ($preview) {
                $this->preview = $preview; // set on the screen, not on this card
            })
            ->start();
    }
}

What changes

handleAsyncCompletion() now looks at the object the closure was written in.

  • If it is a child component that is still mounted on this screen, the closure runs against that child.
  • If that child has unmounted, or a new instance has replaced it under the same key, the result is dropped. A scoped task is already dropped the same way once its screen is no longer topmost.
  • Any other closure is bound to the screen, as before. Static closures still run without $this.

What to watch for

A callback that worked around this by writing to the screen from inside a child will now write to the child. I don't know of any code that relies on that, and it reads as a bug where it does.

Testing

Two new tests in AsyncTaskCompletionTest:

  • A child's finished() callback sets the child's property and leaves the screen's alone.
  • A child that has left the screen gets nothing, and the screen gets nothing either.

Both fail on main and pass with the change. The full suite passes, except the six AppStoreConnectBuildNumberLookupTest tests, which fail on main too on my machine (OpenSSL refuses to generate the test key). Pint is clean.

Found in the /dev/null app (NativePHP/dev-null-app#172), where it ships as a Composer patch until this lands.

A finished() or failed() closure written inside a child component was
rebound to the screen when the result arrived, so $this->result = ...
wrote to the screen and the child never saw its result. The closure now
keeps the child as $this while the child is still mounted on the screen.
If the child has unmounted, or a new instance has replaced it under the
same key, the result is dropped, as a scoped task already is once its
screen is no longer topmost. Closures written outside a component are
still bound to the screen.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant