From 2abaff8e1e467877318a3ec151febb5164037b4b Mon Sep 17 00:00:00 2001 From: gwleuverink Date: Wed, 2 Dec 2026 00:38:54 +0100 Subject: [PATCH 01/12] Say that the work of an async task may use $this --- .../mobile/4/digging-deeper/async-tasks.md | 56 ++++++++++++++----- 1 file changed, 41 insertions(+), 15 deletions(-) diff --git a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md index 1486245d..1d7395d0 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -41,33 +41,59 @@ use [Queues](queues) instead. -## The work closure must be static +## The work closure -The work runs in a **different PHP thread** with its own memory. It cannot see `$this`, your component's -properties, or anything else from the dispatching thread — so the closure must be declared `static`: +The work runs in a **different PHP runtime** of your app, on a thread of its own and with its own memory. Your closure +is sent there along with everything it needs, and all of that arrives as a **copy**. Once the work is done, its result +comes back to the runtime of your screens, where `finished()` and `failed()` run. + +### Passing data to the work + +The work may use any variable that your closure captures, with `use` or as an arrow function: ```php -// ✅ Static — nothing captured from the component -AsyncTask::dispatch(static fn () => Report::build()); +$month = $this->month; -// ❌ Throws InvalidArgumentException at dispatch time -AsyncTask::dispatch(fn () => Report::build($this->month)); +AsyncTask::dispatch(fn () => Report::build($month)); ``` -A non-static closure throws immediately, in your handler, where you can see it — not silently in a background -log. +Arrays, enums, dates and collections arrive as they were. A captured model or Eloquent collection is loaded from the +database again when the work starts, so you should save your changes before you dispatch the task. A model that was +never saved can't be found then, and the task fails with a `ModelNotFoundException`. + +### Using `$this` -Pass data in by capturing plain serializable values with `use` or a shorthand closure: +The work may also use `$this`, to read the properties of your screen and to call its methods, the protected and private +ones included: ```php -$month = $this->month; +use Native\Mobile\Edge\NativeComponent; + +class ReportScreen extends NativeComponent +{ + public int $month = 11; + + public array $report = []; -AsyncTask::dispatch(static fn () => Report::build($month)); + public function generateReport(): void + { + $this->async(fn () => $this->buildReport()) + ->finished(fn (array $report) => $this->report = $report); + } + + protected function buildReport(): array + { + return Report::forMonth($this->month)->toArray(); + } +} ``` -Everything the closure captures must be serializable. An open file, a database connection or a generator can't -cross the thread boundary, so a task that captures one never starts. Its `failed()` callback receives the reason -right away. Without a `failed()` callback, the reason only shows in the log. +In a screen, `$this->async()` is a shorter way to write `AsyncTask::dispatch()`. Both of them accept a method as well, +such as `$this->async($this->buildReport(...))`. + +You may use `$this` in a [nested component](../the-basics/nested-components), a service or an action class too. The +work then takes a copy of that object along. The callbacks that you write in a nested component still run on that +component, and in any other class they are bound to your screen. ## Handling results From e9484fab76d58ec03c7e3eb1bf0aaa4f42e3076f Mon Sep 17 00:00:00 2001 From: gwleuverink Date: Wed, 2 Dec 2026 00:38:55 +0100 Subject: [PATCH 02/12] Document the copy that the work of an async task runs on --- .../mobile/4/digging-deeper/async-tasks.md | 151 ++++++++++++++++++ 1 file changed, 151 insertions(+) diff --git a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md index 1d7395d0..2104426d 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -95,6 +95,157 @@ You may use `$this` in a [nested component](../the-basics/nested-components), a work then takes a copy of that object along. The callbacks that you write in a nested component still run on that component, and in any other class they are bound to your screen. +### The work runs on a copy + +Your screen can't leave the runtime it lives in, so in the work `$this` is a copy of it. When the work assigns a +property, it changes the copy, and the copy is gone once the task is done: + +```php +// The work runs on a copy of the screen, so your screen never sees this total. +$this->async(function () { + $this->total = Order::sum('amount'); +}); +``` + +Return the value from the work instead, and assign it in `finished()`, which runs on your screen: + +```php +$this->async(fn () => (int) Order::sum('amount')) + ->finished(fn (int $total) => $this->total = $total); +``` + +The same is true for the objects that your screen holds. When the work calls `$this->cart->add($product)`, it adds the +product to a copy of the cart. + +| Code | Where it runs | What `$this` is | +| --- | --- | --- | +| The work, and any closure inside it | In the background | A copy of your screen | +| `finished()` and `failed()` | On the UI thread | Your screen | +| An `#[On]` method that hears an event from the task | On the UI thread | The live screen | + +The copy doesn't follow your screen either. It is made when the task starts, at the end of the statement that +dispatches it, and a later change to your screen doesn't reach the work: + +```php +public function generateReport(): void +{ + $this->async(fn () => $this->buildReport()) + ->finished(fn (array $report) => $this->report = $report); + + $this->month = 12; // the task still builds the report of month 11 +} +``` + +If your user may pick another month while the task runs, you may return the month along with the result, and check it +in `finished()`: + +```php +$this->async(fn () => ['month' => $this->month, 'rows' => $this->buildReport()]) + ->finished(function (array $result) { + if ($result['month'] !== $this->month) { + return; // the user is looking at another month + } + + $this->report = $result['rows']; + }); +``` + +### What the copy has + +The copy has everything that your own classes keep on the screen: + +- every property, public, protected or private, with the value it has when the task starts. The properties of your + parent classes and your traits are included; +- the route params, the navigation data and the query, so `param()`, `data()` and `query()` work; +- every method. A `#[Computed]` property is computed again on the copy. + +A model that your screen holds in a property travels as it is, with the changes that are not saved yet. Only a model +that the closure captures in a variable is loaded again. + +A closure inside the work, such as one that you pass to `DB::transaction()` or to a collection, runs on the same copy. +Two tasks never share one: each closure of [`AsyncTask::all()`](#grouping-tasks) has a copy of its own. + +What NativePHP keeps on the screen stays behind: the other screens, the parent and the children of a nested component, +the event listeners and the validation errors. The copy isn't constructed or mounted, so the constructor and `mount()` +don't run for it. + +### What the copy can't do + +The copy isn't on the screen, so nothing it does is rendered. The methods that would have to reach a screen throw a +`LogicException` in the work, which fails the task: `navigate()`, `replace()`, `back()`, `exitToWeb()`, `dispatch()`, +`emit()`, `setNavBar()` and `setTabBar()`. You may call them in `finished()`: + +```php +$this->async(fn () => $this->placeOrder()) + ->finished(fn (int $orderId) => $this->navigate("/orders/{$orderId}")); +``` + +A URL outside your app takes no screen, so `navigate('https://nativephp.com')` still opens the browser. + +The `finished()` and `failed()` callbacks of a task stay in the runtime that dispatches it. So if the work calls +`$this->async()` itself, the callbacks of that task never run. To run one task after another, start the next one in +`finished()`: + +```php +$this->async(fn () => $this->downloadInvoices()) + ->finished(function (array $paths) { + $this->async(fn () => $this->mergeInvoices($paths)) + ->finished(fn (string $path) => $this->invoicePath = $path); + }); +``` + +When `validate()` fails in the work, the task fails with a `ValidationException` and your screen shows no errors. You +should validate before you dispatch the task. To tell your screen something while the work still runs, you may +[send an event](#sending-events-while-a-task-runs). + +### What can't be sent + +Everything the work takes along must be serializable. A task never starts when it takes along one of these, in a +captured variable or, if the work uses `$this`, in a property of your screen: + +- an open file or another resource, or a database connection; +- a generator, or an object of an anonymous class; +- a closure in a property with the type `Closure`; +- Laravel's container, or a service that holds it. + +The `failed()` callback receives the reason right away. For a screen that keeps an open file, for example: + +```text +The async work could not be serialized: $this holds a resource, such as an open file or a connection. Work +that uses $this takes the whole object along. Copy what it needs into variables first. +``` + +Without a `failed()` callback, the reason only shows in the log. If you call `start()` yourself at the end of the chain, +it throws the reason as an `InvalidArgumentException` in your handler. + +Often the best answer is to capture what the work needs, and to open the file or resolve the service in the work: + +```php +// This screen keeps a service that holds Laravel's container, so a copy of the screen can't be sent. +$this->async(fn () => $this->reports->forMonth($this->month)); + +// This only takes the month along, and resolves the service in the work. +$month = $this->month; + +$this->async(fn () => app(ReportService::class)->forMonth($month)); +``` + +### Static closures + +A closure that doesn't mention `$this` leaves your screen behind. You may also declare it `static`, so it has no `$this` +to begin with and can only use the variables you give it: + +```php +$month = $this->month; + +AsyncTask::dispatch(static fn () => Report::build($month)); +``` + +This is a good choice when the work needs a few values. Nothing of your screen travels, so a long list in one of its +properties costs nothing, and there is no copy to assign to by mistake. If `$this` slips in anyway, the task fails with +"Using $this when not in object context". When the work needs several properties or calls the methods of your screen, +using `$this` keeps your code simpler. + ## Handling results ### `finished()` From fb50c54e8644f6b1c23dab3536824661b5f1e612 Mon Sep 17 00:00:00 2001 From: gwleuverink Date: Wed, 2 Dec 2026 00:38:55 +0100 Subject: [PATCH 03/12] Document how the fake runs work that uses $this --- resources/views/docs/mobile/4/digging-deeper/async-tasks.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md index 2104426d..bc4e45f2 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -636,7 +636,11 @@ Available assertions: `assertDispatched()` (optionally with a filter closure), ` `assertDispatchedTimes()`, and `assertShared('alias')`. The work passes the same checks as in your app before it runs, so a closure that captures an open file is refused in -your test as well. +your test as well. Work that uses `$this` runs on a copy of your screen, so an assignment to `$this` in the work is lost +in your test too. + +An object that the work captures in a variable is the one of your test, though, while your app would give the work a +copy of it. So your test should look at what the work returns. A [group](#grouping-tasks) runs its tasks inline too, in the order of your array, and each of them is recorded as a dispatch. `wait()` gives you the results at once: From 41889e5a0e5bb214d9efa0f5b9ea938d232bd983 Mon Sep 17 00:00:00 2001 From: gwleuverink Date: Wed, 2 Dec 2026 00:38:55 +0100 Subject: [PATCH 04/12] Put the closures right in the async task reminders --- resources/views/docs/mobile/4/digging-deeper/async-tasks.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md index bc4e45f2..e70d84d3 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -682,7 +682,9 @@ the callbacks run on your UI thread, in your component. ## Remember! -- The work closure must be `static` and everything it captures must be serializable. +- The work runs in another PHP runtime of your app. Everything it takes along is copied there and must be serializable, + your screen included if the work uses `$this`. +- An assignment to `$this` in the work changes the copy. Return the value, and assign it in `finished()`. - Results round-trip as JSON — return scalars and arrays; pass large data by file path or cache key. - Tasks run once, with no automatic retry. - `wait()` holds your screen until the whole group is done, so keep it for short work. From 62b7cc041a9d047e6b0bf5dac764755735c3c440 Mon Sep 17 00:00:00 2001 From: gwleuverink Date: Wed, 2 Dec 2026 00:41:13 +0100 Subject: [PATCH 05/12] Say that callbacks run in the runtime of your screens --- resources/views/docs/mobile/4/digging-deeper/async-tasks.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md index e70d84d3..65f7c8b1 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -120,8 +120,8 @@ product to a copy of the cart. | Code | Where it runs | What `$this` is | | --- | --- | --- | | The work, and any closure inside it | In the background | A copy of your screen | -| `finished()` and `failed()` | On the UI thread | Your screen | -| An `#[On]` method that hears an event from the task | On the UI thread | The live screen | +| `finished()` and `failed()` | In the runtime of your screens | Your screen | +| An `#[On]` method that hears an event from the task | In the runtime of your screens | The live screen | The copy doesn't follow your screen either. It is made when the task starts, at the end of the statement that dispatches it, and a later change to your screen doesn't reach the work: From ae5658b79884668cf47174cc31ed71c3688bb0f4 Mon Sep 17 00:00:00 2001 From: gwleuverink Date: Wed, 2 Dec 2026 10:52:43 +0100 Subject: [PATCH 06/12] Tighten the start of The work closure --- .../mobile/4/digging-deeper/async-tasks.md | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md index 41fa672a..fdb9bd79 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -43,9 +43,9 @@ use [Queues](queues) instead. ## The work closure -The work runs in a **different PHP runtime** of your app, on a thread of its own and with its own memory. Your closure -is sent there along with everything it needs, and all of that arrives as a **copy**. Once the work is done, its result -comes back to the runtime of your screens, where `finished()` and `failed()` run. +The work runs in a **different PHP runtime** of your app, on a thread of its own with its own memory. Your closure and +everything it needs arrive there as a **copy**, and the result comes back to the runtime of your screens, where +`finished()` and `failed()` run. ### Passing data to the work @@ -58,13 +58,12 @@ AsyncTask::dispatch(fn () => Report::build($month)); ``` Arrays, enums, dates and collections arrive as they were. A captured model or Eloquent collection is loaded from the -database again when the work starts, so you should save your changes before you dispatch the task. A model that was -never saved can't be found then, and the task fails with a `ModelNotFoundException`. +database again when the work starts, so save your changes before you dispatch the task. A model that was never saved +can't be found then, and the task fails with a `ModelNotFoundException`. ### Using `$this` -The work may also use `$this`, to read the properties of your screen and to call its methods, the protected and private -ones included: +The work may also read the properties of your screen and call its methods, the protected and private ones included: ```php use Native\Mobile\Edge\NativeComponent; @@ -88,12 +87,12 @@ class ReportScreen extends NativeComponent } ``` -In a screen, `$this->async()` is a shorter way to write `AsyncTask::dispatch()`. Both of them accept a method as well, -such as `$this->async($this->buildReport(...))`. +In a screen, `$this->async()` is short for `AsyncTask::dispatch()`. Both also accept a method, such as +`$this->async($this->buildReport(...))`. -You may use `$this` in a [nested component](../the-basics/nested-components), a service or an action class too. The -work then takes a copy of that object along. The callbacks that you write in a nested component still run on that -component, and in any other class they are bound to your screen. +You may use `$this` in a [nested component](../the-basics/nested-components), a service or an action class too, and the +work takes a copy of that object along. Callbacks written in a nested component run on that component, and in any other +class they are bound to your screen. ### The work runs on a copy From 02681ee2c4b5e4c8a0b949488e932acc530c9c11 Mon Sep 17 00:00:00 2001 From: gwleuverink Date: Wed, 2 Dec 2026 10:52:57 +0100 Subject: [PATCH 07/12] Fold What the copy has into The work runs on a copy --- .../mobile/4/digging-deeper/async-tasks.md | 67 ++++--------------- 1 file changed, 13 insertions(+), 54 deletions(-) diff --git a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md index fdb9bd79..d5b2e3d2 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -96,73 +96,32 @@ class they are bound to your screen. ### The work runs on a copy -Your screen can't leave the runtime it lives in, so in the work `$this` is a copy of it. When the work assigns a -property, it changes the copy, and the copy is gone once the task is done: +Your screen can't leave the runtime it lives in, so in the work `$this` is a copy of it. An assignment in the work +changes the copy, which is gone once the task is done. Return the value instead, and assign it in `finished()`: ```php -// The work runs on a copy of the screen, so your screen never sees this total. +// ❌ Changes the copy, so your screen never sees this total $this->async(function () { $this->total = Order::sum('amount'); }); -``` - -Return the value from the work instead, and assign it in `finished()`, which runs on your screen: -```php +// ✅ Returns the total, and finished() assigns it on your screen $this->async(fn () => (int) Order::sum('amount')) ->finished(fn (int $total) => $this->total = $total); ``` -The same is true for the objects that your screen holds. When the work calls `$this->cart->add($product)`, it adds the -product to a copy of the cart. - -| Code | Where it runs | What `$this` is | -| --- | --- | --- | -| The work, and any closure inside it | In the background | A copy of your screen | -| `finished()` and `failed()` | In the runtime of your screens | Your screen | -| An `#[On]` method that hears an event from the task | In the runtime of your screens | The live screen | - -The copy doesn't follow your screen either. It is made when the task starts, at the end of the statement that -dispatches it, and a later change to your screen doesn't reach the work: - -```php -public function generateReport(): void -{ - $this->async(fn () => $this->buildReport()) - ->finished(fn (array $report) => $this->report = $report); - - $this->month = 12; // the task still builds the report of month 11 -} -``` - -If your user may pick another month while the task runs, you may return the month along with the result, and check it -in `finished()`: - -```php -$this->async(fn () => ['month' => $this->month, 'rows' => $this->buildReport()]) - ->finished(function (array $result) { - if ($result['month'] !== $this->month) { - return; // the user is looking at another month - } - - $this->report = $result['rows']; - }); -``` - -### What the copy has - -The copy has everything that your own classes keep on the screen: - -- every property, public, protected or private, with the value it has when the task starts. The properties of your - parent classes and your traits are included; -- the route params, the navigation data and the query, so `param()`, `data()` and `query()` work; -- every method. A `#[Computed]` property is computed again on the copy. +The same goes for the objects that your screen holds: when the work calls `$this->cart->add($product)`, it adds the +product to a copy of the cart. Only the work, and any closure inside it, runs on the copy. `finished()` and `failed()` +run on your screen, and an `#[On]` method that hears an event from the task runs on the live screen. -A model that your screen holds in a property travels as it is, with the changes that are not saved yet. Only a model -that the closure captures in a variable is loaded again. +The copy is made when the task starts, at the end of the statement that dispatches it, so a later change to your screen +doesn't reach the work. The copy has every property of your screen, public, protected or private, with the value it has +at that moment, those of your parent classes and traits included. `param()`, `data()` and `query()` work, and a +`#[Computed]` property is computed again. A model in a property travels as it is, with its unsaved changes. Only a +model that the closure captures in a variable is loaded again. A closure inside the work, such as one that you pass to `DB::transaction()` or to a collection, runs on the same copy. -Two tasks never share one: each closure of [`AsyncTask::all()`](#grouping-tasks) has a copy of its own. +Each closure of [`AsyncTask::all()`](#grouping-tasks) has a copy of its own. What NativePHP keeps on the screen stays behind: the other screens, the parent and the children of a nested component, the event listeners and the validation errors. The copy isn't constructed or mounted, so the constructor and `mount()` From 2543532785eed38ce0caf416861ff1610ed688a4 Mon Sep 17 00:00:00 2001 From: gwleuverink Date: Wed, 2 Dec 2026 10:53:07 +0100 Subject: [PATCH 08/12] Tighten What the copy can't do --- .../mobile/4/digging-deeper/async-tasks.md | 27 +++++++------------ 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md index d5b2e3d2..83146766 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -129,32 +129,23 @@ don't run for it. ### What the copy can't do -The copy isn't on the screen, so nothing it does is rendered. The methods that would have to reach a screen throw a -`LogicException` in the work, which fails the task: `navigate()`, `replace()`, `back()`, `exitToWeb()`, `dispatch()`, -`emit()`, `setNavBar()` and `setTabBar()`. You may call them in `finished()`: +Nothing the copy does is rendered. The methods that need a screen throw a `LogicException` in the work, which fails +the task: `navigate()`, `replace()`, `back()`, `exitToWeb()`, `dispatch()`, `emit()`, `setNavBar()` and +`setTabBar()`. Call them in `finished()` instead: ```php $this->async(fn () => $this->placeOrder()) ->finished(fn (int $orderId) => $this->navigate("/orders/{$orderId}")); ``` -A URL outside your app takes no screen, so `navigate('https://nativephp.com')` still opens the browser. +A URL outside your app takes no screen, so `navigate('https://nativephp.com')` in the work still opens the browser. To +tell your screen something while the work runs, you may [send an event](#sending-events-while-a-task-runs). -The `finished()` and `failed()` callbacks of a task stay in the runtime that dispatches it. So if the work calls -`$this->async()` itself, the callbacks of that task never run. To run one task after another, start the next one in -`finished()`: +The callbacks of a task stay in the runtime that dispatches it, so when the work calls `$this->async()` itself, the +callbacks of that task never run. To run one task after another, start the next one in `finished()`. -```php -$this->async(fn () => $this->downloadInvoices()) - ->finished(function (array $paths) { - $this->async(fn () => $this->mergeInvoices($paths)) - ->finished(fn (string $path) => $this->invoicePath = $path); - }); -``` - -When `validate()` fails in the work, the task fails with a `ValidationException` and your screen shows no errors. You -should validate before you dispatch the task. To tell your screen something while the work still runs, you may -[send an event](#sending-events-while-a-task-runs). +When `validate()` fails in the work, the task fails with a `ValidationException` and your screen shows no errors, so +validate before you dispatch the task. ### What can't be sent From b0872174ba6f2af66cfd54f15a8bfdb7e4f9cc2b Mon Sep 17 00:00:00 2001 From: gwleuverink Date: Wed, 2 Dec 2026 10:53:20 +0100 Subject: [PATCH 09/12] Tighten What can't be sent and Static closures --- .../mobile/4/digging-deeper/async-tasks.md | 33 +++++-------------- 1 file changed, 9 insertions(+), 24 deletions(-) diff --git a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md index 83146766..adc29c18 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -157,23 +157,16 @@ captured variable or, if the work uses `$this`, in a property of your screen: - a closure in a property with the type `Closure`; - Laravel's container, or a service that holds it. -The `failed()` callback receives the reason right away. For a screen that keeps an open file, for example: +The `failed()` callback receives the reason right away, and without one the reason only shows in the log. If you call +`start()` yourself at the end of the chain, it throws the reason as an `InvalidArgumentException` in your handler. -```text -The async work could not be serialized: $this holds a resource, such as an open file or a connection. Work -that uses $this takes the whole object along. Copy what it needs into variables first. -``` - -Without a `failed()` callback, the reason only shows in the log. If you call `start()` yourself at the end of the chain, -it throws the reason as an `InvalidArgumentException` in your handler. - -Often the best answer is to capture what the work needs, and to open the file or resolve the service in the work: +Capture what the work needs instead, and open the file or resolve the service in the work: ```php -// This screen keeps a service that holds Laravel's container, so a copy of the screen can't be sent. +// ❌ The screen keeps a service that holds Laravel's container, so its copy can't be sent $this->async(fn () => $this->reports->forMonth($this->month)); -// This only takes the month along, and resolves the service in the work. +// ✅ Only the month travels, and the service is resolved in the work $month = $this->month; $this->async(fn () => app(ReportService::class)->forMonth($month)); @@ -182,18 +175,10 @@ $this->async(fn () => app(ReportService::class)->forMonth($month)); ### Static closures A closure that doesn't mention `$this` leaves your screen behind. You may also declare it `static`, so it has no `$this` -to begin with and can only use the variables you give it: - -```php -$month = $this->month; - -AsyncTask::dispatch(static fn () => Report::build($month)); -``` - -This is a good choice when the work needs a few values. Nothing of your screen travels, so a long list in one of its -properties costs nothing, and there is no copy to assign to by mistake. If `$this` slips in anyway, the task fails with -"Using $this when not in object context". When the work needs several properties or calls the methods of your screen, -using `$this` keeps your code simpler. +to begin with and can only use the variables you give it. This is a good choice when the work needs a few values: +nothing of your screen travels, so a long list in one of its properties costs nothing, and there is no copy to assign +to by mistake. If `$this` slips in anyway, the task fails with "Using $this when not in object context". When the work +needs several properties or calls the methods of your screen, using `$this` keeps your code simpler. ## Handling results From 7f07f1c6d43d27a9e287c25a127c55ce0886c09d Mon Sep 17 00:00:00 2001 From: gwleuverink Date: Wed, 2 Dec 2026 10:53:30 +0100 Subject: [PATCH 10/12] Say in one paragraph how the fake treats work that uses $this --- .../views/docs/mobile/4/digging-deeper/async-tasks.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md index adc29c18..88242c31 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -511,11 +511,9 @@ Available assertions: `assertDispatched()` (optionally with a filter closure), ` `assertDispatchedTimes()`, and `assertShared('alias')`. The work passes the same checks as in your app before it runs, so a closure that captures an open file is refused in -your test as well. Work that uses `$this` runs on a copy of your screen, so an assignment to `$this` in the work is lost -in your test too. - -An object that the work captures in a variable is the one of your test, though, while your app would give the work a -copy of it. So your test should look at what the work returns. +your test as well. Work that uses `$this` runs on a copy of your screen here too, so an assignment to `$this` in the +work is lost. An object that the work captures in a variable is the one of your test, though, where your app would +send a copy, so your test should look at what the work returns. A [group](#grouping-tasks) runs its tasks inline too, in the order of your array, each recorded as a dispatch, and `wait()` returns the results at once. Every task runs, also the ones after a task that failed. Without the fake no task From ed7e2dc76532e5f9b08efa8d7ace4fff6bd57f32 Mon Sep 17 00:00:00 2001 From: gwleuverink Date: Wed, 2 Dec 2026 10:54:56 +0100 Subject: [PATCH 11/12] Say once which code runs on the copy --- .../mobile/4/digging-deeper/async-tasks.md | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md index 88242c31..93d58ade 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -44,8 +44,7 @@ use [Queues](queues) instead. ## The work closure The work runs in a **different PHP runtime** of your app, on a thread of its own with its own memory. Your closure and -everything it needs arrive there as a **copy**, and the result comes back to the runtime of your screens, where -`finished()` and `failed()` run. +everything it needs arrive there as a **copy**, and the result comes back to the runtime of your screens. ### Passing data to the work @@ -111,17 +110,17 @@ $this->async(fn () => (int) Order::sum('amount')) ``` The same goes for the objects that your screen holds: when the work calls `$this->cart->add($product)`, it adds the -product to a copy of the cart. Only the work, and any closure inside it, runs on the copy. `finished()` and `failed()` -run on your screen, and an `#[On]` method that hears an event from the task runs on the live screen. +product to a copy of the cart. `finished()` and `failed()` run on your screen, and an `#[On]` method that hears an +event from the task runs on the live screen. The copy is made when the task starts, at the end of the statement that dispatches it, so a later change to your screen -doesn't reach the work. The copy has every property of your screen, public, protected or private, with the value it has -at that moment, those of your parent classes and traits included. `param()`, `data()` and `query()` work, and a -`#[Computed]` property is computed again. A model in a property travels as it is, with its unsaved changes. Only a -model that the closure captures in a variable is loaded again. +doesn't reach the work. A closure inside the work, such as one that you pass to `DB::transaction()` or to a collection, +runs on the same copy. Each closure of [`AsyncTask::all()`](#grouping-tasks) has a copy of its own. -A closure inside the work, such as one that you pass to `DB::transaction()` or to a collection, runs on the same copy. -Each closure of [`AsyncTask::all()`](#grouping-tasks) has a copy of its own. +The copy has every property of your screen, public, protected or private, with the value it has when the task starts, +those of your parent classes and traits included. `param()`, `data()` and `query()` work, and a `#[Computed]` property +is computed again. A model in a property travels as it is, with its unsaved changes. Only a model that the closure +captures in a variable is loaded again. What NativePHP keeps on the screen stays behind: the other screens, the parent and the children of a nested component, the event listeners and the validation errors. The copy isn't constructed or mounted, so the constructor and `mount()` From 1ff0be3d1a1f88f68334d414f1fef3d3f4037f1e Mon Sep 17 00:00:00 2001 From: gwleuverink Date: Wed, 2 Dec 2026 10:56:22 +0100 Subject: [PATCH 12/12] Show the $this sample as two methods, as the page's other samples do --- .../mobile/4/digging-deeper/async-tasks.md | 23 ++++++------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md index 93d58ade..dc45c394 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -65,24 +65,15 @@ can't be found then, and the task fails with a `ModelNotFoundException`. The work may also read the properties of your screen and call its methods, the protected and private ones included: ```php -use Native\Mobile\Edge\NativeComponent; - -class ReportScreen extends NativeComponent +public function generateReport(): void { - public int $month = 11; - - public array $report = []; - - public function generateReport(): void - { - $this->async(fn () => $this->buildReport()) - ->finished(fn (array $report) => $this->report = $report); - } + $this->async(fn () => $this->buildReport()) + ->finished(fn (array $report) => $this->report = $report); +} - protected function buildReport(): array - { - return Report::forMonth($this->month)->toArray(); - } +protected function buildReport(): array +{ + return Report::forMonth($this->month)->toArray(); } ```