Combine 响应式编程框架的详细讲解和实现方法

Combine 响应式编程框架的详细讲解和实现方法

什么是 Combine?

Combine 是 Apple 在 iOS 13+ 推出的响应式编程框架 ,用于处理 异步事件流(如网络请求、UI输入、通知等) ,替代回调、KVO 和 NotificationCenter 等传统写法。

示例一:基本使用

swift 复制代码
import Combine

var cancellables = Set<AnyCancellable>()
let publisher = Just("Hello Combine")
publisher
    .sink(receiveCompletion: { completion in
        print("完成状态: \(completion)")
    }, receiveValue: { value in
        print("接收到的值: \(value)")
    })
    .store(in: &cancellables)

示例二:使用 URLSession 数据请求

swift 复制代码
import Foundation
import Combine

struct Post: Codable {
    let id: Int
    let title: String
}

var cancellables = Set<AnyCancellable>()

let url = URL(string: "https://jsonplaceholder.typicode.com/posts/1")!

URLSession.shared.dataTaskPublisher(for: url)
    .map(\.data)
    .decode(type: Post.self, decoder: JSONDecoder())
    .sink(receiveCompletion: { completion in
        switch completion {
        case .finished:
            print("请求完成")
        case .failure(let error):
            print("错误: \(error)")
        }
    }, receiveValue: { post in
        print("标题: \(post.title)")
    })
    .store(in: &cancellables)

@Published + ViewModel 绑定(MVVM)

swift 复制代码
class ViewModel: ObservableObject {
    @Published var searchText: String = ""
    @Published var result: String = ""

    private var cancellables = Set<AnyCancellable>()

    init() {
        $searchText
            .debounce(for: .milliseconds(300), scheduler: RunLoop.main)
            .removeDuplicates()
            .map { "结果为:\($0.uppercased())" }
            .assign(to: &$result)
    }
}

绑定在 SwiftUI 中使用:

swift 复制代码
struct ContentView: View {
    @StateObject var viewModel = ViewModel()

    var body: some View {
        VStack {
            TextField("输入", text: $viewModel.searchText)
            Text(viewModel.result)
        }
        .padding()
    }
}

🎯 使用场景总结

🚫 注意事项

  • Combine 仅适用于 iOS 13+、macOS 10.15+****
  • 链式调用中别忘记 .store(in:) 否则会立即释放

🎯 CombineRxSwift 的对比和选择

  • 使用 SwiftUI 构建 App:优先使用 Combine****
  • 使用 UIKit 构建 App:优先使用 RxSwift****
  • 全新项目、仅支持 iOS 13+:Combine 更轻量****
  • 已使用 RxSwift 或需兼容 iOS 12 及更低版本:继续用 RxSwift
相关推荐
笑尘pyrotechnic7 小时前
DocC的简单使用
ios·objective-c
小悟空8 小时前
[AI 生成] Flink 面试题
大数据·面试·flink
谈吐大方的鹏sir9 小时前
SwiftUI-Text组件学习
ios
Sherry00710 小时前
CSS Grid 交互式指南(译)(下)
css·面试
一只毛驴10 小时前
浏览器中的事件冒泡,事件捕获,事件委托
前端·面试
一只叫煤球的猫10 小时前
你真的处理好 null 了吗?——11种常见但容易被忽视的空值处理方式
java·后端·面试
不自律的笨鸟10 小时前
iOS 26,双版本更新来了
ios·iphone
KarrySmile10 小时前
Day04–链表–24. 两两交换链表中的节点,19. 删除链表的倒数第 N 个结点,面试题 02.07. 链表相交,142. 环形链表 II
算法·链表·面试·双指针法·虚拟头结点·环形链表
一只毛驴11 小时前
谈谈浏览器的DOM事件-从0级到2级
前端·面试
在未来等你11 小时前
RabbitMQ面试精讲 Day 5:Virtual Host与权限控制
中间件·面试·消息队列·rabbitmq