swift_combine

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Swift Combine

Swift Combine

This skill covers Apple's Combine framework for reactive programming and handling asynchronous events.
本技能涵盖了苹果用于响应式编程和处理异步事件的Combine框架。

Overview

概述

Combine is a declarative Swift API for processing values over time. It provides a unified approach to handling asynchronous events, user interface updates, and data streams.
Combine是一个用于随时间处理值的声明式Swift API。它提供了统一的方式来处理异步事件、用户界面更新和数据流。

Available References

可用参考资料

  • Publishers & Subscribers - Core concepts and lifecycle
  • Operators - Transforming, filtering, and combining streams
  • Integration - Using Combine with UIKit, SwiftUI, and Foundation
  • 发布者与订阅者 - 核心概念与生命周期
  • 操作符 - 转换、过滤和组合数据流
  • 集成 - 在UIKit、SwiftUI和Foundation中使用Combine

Quick Reference

快速参考

Basic Publisher

基础发布者

swift
import Combine

// Published property
@Published var username: String = ""

// CurrentValueSubject
let subject = CurrentValueSubject<String, Never>("initial")

// PassthroughSubject
let passthrough = PassthroughSubject<Int, Never>()

// Just publisher
let just = Just("value")

// Future publisher
let future = Future<String, Error> { promise in
    promise(.success("result"))
}
swift
import Combine

// Published属性
@Published var username: String = ""

// CurrentValueSubject
let subject = CurrentValueSubject<String, Never>("initial")

// PassthroughSubject
let passthrough = PassthroughSubject<Int, Never>()

// Just发布者
let just = Just("value")

// Future发布者
let future = Future<String, Error> { promise in
    promise(.success("result"))
}

Subscribing

订阅

swift
// Sink
let cancellable = publisher.sink(
    receiveCompletion: { completion in
        switch completion {
        case .finished:
            print("Completed")
        case .failure(let error):
            print("Error: \(error)")
        }
    },
    receiveValue: { value in
        print("Value: \(value)")
    }
)

// Assign
let cancellable = publisher
    .assign(to: \.text, on: label)
swift
// Sink
let cancellable = publisher.sink(
    receiveCompletion: { completion in
        switch completion {
        case .finished:
            print("Completed")
        case .failure(let error):
            print("Error: \(error)")
        }
    },
    receiveValue: { value in
        print("Value: \(value)")
    }
)

// Assign
let cancellable = publisher
    .assign(to: \.text, on: label)

Storing Subscriptions

存储订阅

swift
private var cancellables = Set<AnyCancellable>()

publisher
    .sink { value in
        print(value)
    }
    .store(in: &cancellables)
swift
private var cancellables = Set<AnyCancellable>()

publisher
    .sink { value in
        print(value)
    }
    .store(in: &cancellables)

Common Operators

常用操作符

swift
publisher
    .filter { $0 > 0 }
    .map { $0 * 2 }
    .debounce(for: .seconds(0.5), scheduler: RunLoop.main)
    .removeDuplicates()
    .sink { value in
        print(value)
    }
swift
publisher
    .filter { $0 > 0 }
    .map { $0 * 2 }
    .debounce(for: .seconds(0.5), scheduler: RunLoop.main)
    .removeDuplicates()
    .sink { value in
        print(value)
    }

Combine vs Async/Await

Combine vs Async/Await

Use CaseCombineAsync/Await
Event streams✅ Excellent⚠️ Complex
UI bindings✅ Perfect⚠️ Verbose
Chaining operations✅ Great✅ Good
Simple async calls⚠️ Overkill✅ Simple
Error handling✅ Rich✅ Good
使用场景CombineAsync/Await
事件流✅ 出色⚠️ 复杂
UI绑定✅ 完美⚠️ 繁琐
链式操作✅ 优秀✅ 良好
简单异步调用⚠️ 大材小用✅ 简单
错误处理✅ 丰富✅ 良好

Best Practices

最佳实践

  1. Store cancellables - Prevent memory leaks
  2. Use weak self - Avoid retain cycles
  3. Handle errors - Always handle completion
  4. Thread safety - Use receive(on:) for UI
  5. Cancel properly - Clean up subscriptions
  6. Avoid overuse - Combine is powerful but not for everything
  7. Test pipelines - Use expectations for async
  1. 存储cancellables - 防止内存泄漏
  2. 使用weak self - 避免循环引用
  3. 处理错误 - 始终处理完成事件
  4. 线程安全 - 对UI使用receive(on:)
  5. 正确取消 - 清理订阅
  6. 避免过度使用 - Combine功能强大,但并非适用于所有场景
  7. 测试流水线 - 使用期望测试异步操作

For More Information

更多信息

Visit https://swiftzilla.dev for comprehensive Combine documentation.
访问 https://swiftzilla.dev 获取全面的Combine文档。