How to handle long-running operations and stream data in Phoenix LiveView without blocking the main LiveView process or disrupting user experience
Phoenix LiveView provides four async functions that leverage Elixir's lightweight processes for asynchronous work: (1) assign_async/4 for simple data fetching that automatically updates assigned values, (2) stream_async/4 for initial page loads with collection data integrated with Phoenix Streams, (3) start_async/4 and handle_async/3 for complex workflows with full control and cancellation support. Each async operation is managed through Phoenix.LiveView.AsyncResult which tracks status (loading, ok, failed). For streaming scenarios like LLM-style output, use start_async/4 with message passing: spawn a process that sends incremental updates via send(pid, {:message, data}), then handle these messages in handle_info/2 to update the UI in real-time. Example: socket |> start_async(:data_stream, fn -> stream_response(pid) end) where the spawned process sends data chunks that are received and rendered progressively.