Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 121 additions & 16 deletions resources/views/docs/mobile/4/digging-deeper/async-tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,33 +41,134 @@ use [Queues](queues) instead.

</aside>

## 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 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.

### 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 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`.

Pass data in by capturing plain serializable values with `use` or a shorthand closure:
### Using `$this`

The work may also read the properties of your screen and call its methods, the protected and private ones included:

```php
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();
}
```

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, 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

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
// ❌ Changes the copy, so your screen never sees this total
$this->async(function () {
$this->total = Order::sum('amount');
});

// ✅ 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 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. `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. 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()`
don't run for it.

### What the copy can't do

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')` 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 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()`.

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

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, 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.

Capture what the work needs instead, and open the file or resolve the service in the work:

```php
// ❌ 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));

// ✅ Only the month travels, and the service is resolved in the work
$month = $this->month;

AsyncTask::dispatch(static fn () => Report::build($month));
$this->async(fn () => app(ReportService::class)->forMonth($month));
```

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.
### 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. 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

Expand Down Expand Up @@ -400,7 +501,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.
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
Expand All @@ -421,7 +524,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.
Expand Down