여러 스트림

여러 스트림 (Multiple Streams)

하나의 요청에서 여러 개의 streamable UI를 조합해 반환하고, 중첩된 streamable UI를 만드는 방법을 설명하는 문서예요.

출처: 문서

본문

여러 Streamable UI (Multiple Streamable UIs)

AI SDK RSC API는 단일 요청에서 원하는 만큼의 streamable UI를 다른 데이터와 함께 조합해 반환할 수 있게 해 줘요. 이는 UI를 더 작은 컴포넌트로 분리해 각각 별도로 스트리밍하고 싶을 때 유용해요.

'use server';

import { createStreamableUI } from '@ai-sdk/rsc';

export async function getWeather() {
  const weatherUI = createStreamableUI();
  const forecastUI = createStreamableUI();

  weatherUI.update(<div>Loading weather...</div>);
  forecastUI.update(<div>Loading forecast...</div>);

  getWeatherData().then(weatherData => {
    weatherUI.done(<div>{weatherData}</div>);
  });

  getForecastData().then(forecastData => {
    forecastUI.done(<div>{forecastData}</div>);
  });

  // Return both streamable UIs and other data fields.
  return {
    requestedAt: Date.now(),
    weather: weatherUI.value,
    forecast: forecastUI.value,
  };
}

클라이언트 측 코드는 이전 예제와 비슷하지만, 툴 호출이 weather와 forecast UI를 가진 새 데이터 구조를 반환해요. weather와 forecast 데이터를 가져오는 속도에 따라 이 두 컴포넌트는 독립적으로 업데이트될 수 있어요.

중첩된 Streamable UI (Nested Streamable UIs)

다른 UI 컴포넌트 안에서 UI 컴포넌트를 스트리밍할 수 있어요. 이렇게 하면 더 작고 재사용 가능한 컴포넌트로 복잡한 UI를 구성할 수 있어요. 아래 예제에서는 historyChart 스트림을 StockCard 컴포넌트에 prop으로 전달해요. StockCard는 historyChart 스트림을 렌더링할 수 있고, 서버가 새 데이터로 응답할 때 자동으로 업데이트돼요.

async function getStockHistoryChart({ symbol: string }) {
  'use server';

  const ui = createStreamableUI(<Spinner />);

  // We need to wrap this in an async IIFE to avoid blocking.
  (async () => {
    const price = await getStockPrice({ symbol });

    // Show a spinner as the history chart for now.
    const historyChart = createStreamableUI(<Spinner />);
    ui.done(<StockCard historyChart={historyChart.value} price={price} />);

    // Getting the history data and then update that part of the UI.
    const historyData = await fetch('https://my-stock-data-api.com');
    historyChart.done(<HistoryChart data={historyData} />);
  })();

  return ui;
}

더 알아보기 (Learn more)