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
相关推荐
这世界那么多上官婉儿2 分钟前
沉浸式体验事务的一周
后端·面试
NoneCoder3 分钟前
Webpack 剖析与策略
前端·面试·webpack
白露与泡影1 小时前
Java面试避坑指南:牛客网最新高频考点+答案详解
java·开发语言·面试
野盒子2 小时前
前端面试题 微信小程序兼容性问题与组件适配策略
前端·javascript·面试·微信小程序·小程序·cocoa
王中阳Go2 小时前
2025Java面试八股②(含121道面试题和答案)
java·后端·面试
汪子熙3 小时前
QRCode.js:一款轻量级、跨浏览器的 JavaScript 二维码生成库
前端·javascript·面试
小小神仙3 小时前
JSCommon系列 - 前端常用工具库集合
前端·javascript·面试
无知的前端3 小时前
Flutter开发,GetX框架路由相关详细示例
android·flutter·ios
知其然亦知其所以然3 小时前
只会写 Mapper 就想进大厂?MyBatis 原理你真懂了吗?
java·后端·面试
大熊猫侯佩3 小时前
iOS 18 中全新 SwiftData 重装升级,其中一个功能保证你们“爱不释手”
数据库·ios·swift