[转] Combine学习笔记 - What is Combine?
参考链接: https://github.com/AvdLee/CombineSwiftPlayground6个月前 • 182次点击 • 来自 移动端
标签: Swift
What is Combine?
- A declarative Swift API for processing values over time
- "Customize handling of asynchronous events by combining event-processing operators."
Combine是用于处理事件流的声明式编程框架
大部分介绍Combine文章的第一个示例大致如下:
Just(5)
.map { _ -> String in
// do something with the incoming value here
// and return a string
"a string"
}
.sink { receivedValue in
// sink is the subscriber and terminates the pipeline
print("The end result was \(receivedValue)")
}
它清晰的描述了发布者Publisher
,操作符Operator
,订阅者Subsciber
三者间的关系,对有reactive programming
编程经验的开发者而言更是一目了然
没接触过函数响应式编程的朋友请阅读:Using Combine - 函数响应式编程
关于 Combine 的核心概念请阅读:Using Combine - 核心概念
import Combine
[1, 2, 3].publisher
.map { int in "Number: \(int)" }
.sink(receiveValue: { int in
print(int)
})
[1, 2, nil, 3, nil, 4, nil, 5].publisher
.compactMap { $0 }
.sink(receiveValue: { int in
print("Received \(int)")
})