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 a9f048e7..3dff0bd1 100644 --- a/resources/views/docs/mobile/4/digging-deeper/async-tasks.md +++ b/resources/views/docs/mobile/4/digging-deeper/async-tasks.md @@ -65,8 +65,9 @@ $month = $this->month; AsyncTask::dispatch(static fn () => Report::build($month)); ``` -Everything the closure captures must be serializable. Resources, PDO handles, and open file pointers can't -cross the thread boundary and will throw. +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. ## Handling results @@ -221,6 +222,123 @@ Each callback fires as its own task completes — there's no ordering guarantee dispatched than the pool has slots for, the extras queue up and run as slots free up. This helps to limit overall memory consumption. +By default, two tasks run at the same time. You may raise that to at most four with the `async.max_slots` option in +`config/nativephp.php`, or the `NATIVEPHP_ASYNC_MAX_SLOTS` environment variable it reads. The change takes effect the +next time you build your app. + +## Grouping tasks + +When a screen needs the results of several tasks together, you may pass the closures to `AsyncTask::all()`. Each +closure runs as a task of its own, and the group reports back once: + +```php +use Native\Mobile\AsyncTask; +use Native\Mobile\Exceptions\AsyncTaskException; + +public function loadDashboard(): void +{ + $this->loading = true; + + AsyncTask::all([ + 'users' => static fn () => User::count(), + 'unpaid' => static fn () => Order::where('paid', false)->count(), + ]) + ->finished(function (array $counts) { + $this->counts = $counts; // ['users' => 120, 'unpaid' => 3] + $this->loading = false; + }) + ->failed(function (AsyncTaskException $e) { + $this->error = $e->getMessage(); + $this->loading = false; + }); +} +``` + +`all()` returns straight away, and its tasks start at the end of the statement. When the whole group is done, your +screen re-renders once. `finished()` receives the results under the keys and in the order of your array, whichever task +was done first, or as a plain list if your array has no keys. As with a single task, return +[scalars and arrays](#handling-results). + +The callbacks are [scoped to the screen](#callbacks-are-scoped-to-the-screen) that started the group, and a group has +no `shared()` method. + +`all()` only takes closures, and anything else throws an `InvalidArgumentException` before any task starts. To run a +[task class](#task-classes) in a group, call its `handle()` method in a closure, such as +`static fn () => app(BuildReport::class)->handle($month)`. + + + +### Failures and timeouts + +The first task that fails settles the group: `failed()` is called once with its `AsyncTaskException`, and `finished()` +is not called. Tasks that have not started by then never run. A task that is already running can't be stopped, so it +runs to its end and its result is dropped. A change it writes may still be saved after `failed()` was called. Without +a `failed()` callback, the failure only leaves a line in the debug log, while `APP_DEBUG` is on. + +Each task may take 60 seconds. You may set another deadline in seconds with `timeout()`, or `0` for none. A task that +passes its deadline fails the group, and the time it waits for a free slot counts toward it: + +```php +AsyncTask::all($requests) + ->timeout(10) + ->failed(function (AsyncTaskException $e) { + $this->error = $e->getMessage(); // The async task did not complete within 10 seconds. + }); +``` + +### Waiting for the results + +When a handler can't go on without the results, you may call `wait()`. It starts the group, holds your handler until +every task is done, and returns the results under their keys: + +```php +public function refresh(): void +{ + $counts = AsyncTask::all([ + 'users' => static fn () => User::count(), + 'unpaid' => static fn () => Order::where('paid', false)->count(), + ])->wait(); + + $this->summary = "{$counts['users']} users, {$counts['unpaid']} unpaid orders"; +} +``` + +While your handler waits, your screen doesn't render, so a spinner that you switch on right before `wait()` never +shows. Taps, other events and polls wait until your handler returns. Keep `wait()` for short work that is done sooner +side by side than one piece after another, and let `finished()` take the results of anything longer. You may also +`start()` the group first, do other work in your handler, and call `wait()` after that. + +When a task fails or passes its deadline, `wait()` throws its `AsyncTaskException`: + +```php +try { + $this->news = AsyncTask::all($requests)->timeout(5)->wait(); +} catch (AsyncTaskException $e) { + $this->error = $e->getMessage(); +} +``` + +If the group has a `failed()` callback, that is called instead and `wait()` returns `null`. A `finished()` callback +runs before `wait()` returns. With `timeout(0)`, a task that never ends holds your screen for good. + +You may only wait in a native screen, such as in a handler, in `mount()`, or in a `#[Poll]` or `#[On]` method. In a +job, in the work of another task and in a web view, `wait()` starts no task and fails with the reason. A single +`dispatch()` has no `wait()` method, so to wait for one task, pass `all()` a single closure. + + + ## Task classes For anything you'd rather not write inline, extend `AsyncTask` and put the work in `handle()`: @@ -281,6 +399,13 @@ $fake->assertDispatched() Available assertions: `assertDispatched()` (optionally with a filter closure), `assertNotDispatched()`, `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. + +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 +runs in a test, so `wait()` fails there with a message that tells you to call `AsyncTask::fake()`. + ## How It Works When you dispatch a task, the work closure is serialized and handed to a background PHP context — a full PHP @@ -299,6 +424,7 @@ the callbacks run on your UI thread, in your component. - The work closure must be `static` and everything it captures must be serializable. - 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. - Scoped callbacks are dropped if the user navigates away from the screen that started the work; use `shared()` when the result matters regardless of what screen the user moves to. - Async tasks don't survive the app being killed. For durable background work, use [Queues](queues).