Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

swift-async-stream-patterns

БесплатноБез исполняемых скриптовНе проверен

Patterns and best practices for building robust AsyncStream and AsyncSequence types, learned from swift-async-algorithms.

nonameplumот nonameplum★ 17 звёзд на GitHub

Об этом скилле

AsyncStream & AsyncSequence Patterns

When to use

  • Building custom AsyncSequence types that produce values over time
  • Bridging synchronous/callback-based APIs to async/await
  • Implementing channels, buffers, or multi-consumer broadcasting
  • Handling backpressure in producer/consumer scenarios
  • Creating "CurrentValue"-like semantics where late subscribers receive buffered values

Core Patterns from swift-async-algorithms

1. State Machine Pattern

Use explicit state machines with enums to model complex async behavior. State machines return actions rather than performing side effects directly. This separates state logic from async operations.

struct ChannelStateMachine<Element: Sendable> {
  private enum State: Sendable {
    case idle
    case buffered(Element)
    case streaming(continuation: Continuation)
    case finished
  }

  private var state: State = .idle

  // Each mutation returns an Action describing what to do
  enum SendAction {
    case yield(continuation: Continuation, element: Element)
    case buffer(element: Element)
    case ignore
  }

  mutating func send(_ element: Element) -> SendAction {
    switch state {
    case .idle:
      state = .buffered(element)
      return .buffer(element: element)
    case .buffered:
      state = .buffered(element)
      return .buffer(element: element)
    case .streaming(let continuation):
      return .yield(continuation: continuation, element: element)
    case .finished:
      return .ignore
    }
  }
}

Key insight: Compute state transitions inside locks, execute side effects (like resuming continuations) OUTSIDE locks.

2. Thread-Safe State with Mutex

Use Mutex from the Synchronization framework (iOS 18+, macOS 15+). The pattern from swift-async-algorithms:

import Synchronization

@available(macOS 15.0, iOS 18.0, *)
final class Channel<Element: Sendable>: Sendable {
  // State is a simple Sendable struct (NOT ~Copyable)
  private struct State: Sendable {
    var bufferedElement: Element?
    var continuation: AsyncStream<Element>.Continuation?
    var isFinished: Bool = false
  }

  // Mutex is stored in the class (class can hold ~Copyable types)
  private let state: Mutex<State>

  init() {
    self.state = Mutex(State())
  }

  func send(_ element: Element) {
    // 1. Determine action INSIDE lock
    let continuation = state.withLock { state -> AsyncStream<Element>.Continuation? in
      guard !state.isFinished else { return nil }
      if let cont = state.continuation {
        return cont
      } else {
        state.bufferedElement = element
        return nil
      }
    }
    // 2. Execute side effect OUTSIDE lock
    continuation?.yield(element)
  }
}

Critical rules:

  1. Use final class to hold Mutex (Mutex is ~Copyable)
  2. State struct should be Sendable, not ~Copyable
  3. Extract continuations inside the lock, resume OUTSIDE to prevent deadlocks
  4. Keep lock durations minimal - no async operations while holding a lock

3. Continuation Safety Patterns

Always handle cancellation properly with continuations:

func next() async -> Element? {
  await withTaskCancellationHandler {
    await withUnsafeContinuation { continuation in
      // Determine action inside lock
      let immediateResult = state.withLock { state -> Element?? in
        if let element = state.buffer.popFirst() {
          return .some(element)
        }
        state.waitingContinuation = continuation
        return nil  // Will be resumed later
      }

      // Handle immediate result OUTSIDE lock
      if let result = immediateResult {
        continuation.resume(returning: result)
      }
    }
  } onCancel: {
    // Called concurrently - must be thread-safe
    let continuation = state.withLock { state -> UnsafeContinuation<Element?, Never>? in
      let cont = state.waitingContinuation
      state.waitingContinuation = nil
      return cont
    }
    continuation?.resume(returning: nil)
  }
}

Critical rules:

  1. onCancel runs concurrently with the main operation - use locks
  2. Never call user code or resume continuations while holding a lock
  3. Always ensure continuations are eventually resumed (success, nil, or cancellation)

4. Buffering Strategies

Model buffering policies explicitly:

enum BufferPolicy: Sendable {
  /// Buffer up to N elements, then suspend producers
  case bounded(Int)

  /// Buffer without limit (use with caution)
  case unbounded

  /// Keep newest N elements, drop oldest when full
  case bufferingNewest(Int)

  /// Keep oldest N elements, drop newest when full
  case bufferingOldest(Int)
}

5. Single-Value Buffering (CurrentValue Pattern)

For scenarios where late subscribers should receive the most recent value. Uses explicit state machine with enum states to make invalid states unrepresentable:

@available(macOS 15.0, iOS 18.0, *)
public final class SingleValueBufferedStream<Element: Sendable>: Sendable {

  priv
Полный SKILL.md на GitHub

Установить swift-async-stream-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл swift-async-stream-patterns?

Patterns and best practices for building robust AsyncStream and AsyncSequence types, learned from swift-async-algorithms.

Как установить скилл swift-async-stream-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл swift-async-stream-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить swift-async-stream-patterns с