> ## Documentation Index
> Fetch the complete documentation index at: https://docs.x.com/llms.txt
> Use this file to discover all available pages before exploring further.

# ストリーミング

> TypeScript でイベントリスナーや非同期イテレーションを使ってサンプリングされた投稿の X API データをリアルタイムに受信します。自動再接続とストリームのライフサイクル制御に対応しています。

TypeScript SDK は、ライブデータフィード向けのリアルタイムストリーミング機能を提供します。

## 基本的なストリーミング

リアルタイムのサンプリングされた投稿に接続します:

<CodeGroup>
  ```typescript title="stream.ts" lines wrap icon="square-js" theme={null} theme={null}
  import { Client } from '@xdevplatform/xdk';

  const client: Client = new Client({ bearerToken: 'your-bearer-token' });

  // 1% sampled public posts
  const stream = await client.stream.postsSample({
    tweetFields: ['id','text','created_at'],
    expansions: ['author_id'],
    userFields: ['id','username','name']
  });

  // Listen to events
  stream.on('data', (event) => {
    // event is the parsed JSON line (data/includes/matching_rules)
    console.log('New data:', event);
  });

  stream.on('error', (e) => console.error('Stream error:', e));
  stream.on('close', () => console.log('Stream closed'));
  ```

  ```javascript stream.js theme={null} theme={null}
  import { Client } from '@xdevplatform/xdk';

  const client = new Client({ bearerToken: 'your-bearer-token' });
  const stream = await client.stream.postsSample({ tweetFields: ['id','text'] });

  stream.on('data', (event) => {
    console.log('New data:', event);
  });
  stream.on('error', (e) => console.error('Stream error:', e));
  stream.on('close', () => console.log('Stream closed'));
  ```
</CodeGroup>

## 非同期イテレーション

非同期イテレーションでストリームを消費します:

<CodeGroup>
  ```typescript async.ts theme={null} theme={null}
  const stream = await client.stream.postsSample();
  for await (const event of stream) {
    // Each event is a parsed JSON line (data/includes/matching_rules)
    console.log(event);
  }
  ```

  ```javascript async.js theme={null} theme={null}
  const stream = await client.stream.postsSample();
  for await (const event of stream) {
    console.log(event);
  }
  ```
</CodeGroup>

## ストリームの管理

イベント駆動型ストリームからライフサイクルを制御します:

```typescript theme={null}
// Close the stream
stream.close();

// Auto-reconnect (if enabled by your wrapper)
// The default EventDrivenStream exposes basic reconnect hooks
```

## エラーハンドリング

ストリーミングのエラーと再接続を処理します:

```typescript theme={null}
stream.on('error', (event) => {
  const err = event.error || event;
  console.error('Stream error:', err);
});

stream.on('keepAlive', () => {
  // heartbeat event
});
```

<Info>
  JavaScript/TypeScript XDK を使った詳細なコードサンプルは、[コードサンプル GitHub リポジトリ](https://github.com/xdevplatform/samples/tree/main/javascript)を参照してください。
</Info>
