let stringPublisher = Just("hello, world!") let uppercasedPublisher = stringPublisher.map { $0.uppercased() }
let arrayPublisher = [1, 2, 3, 4, 5].publisher let oddPublisher = arrayPublisher.filter { $0 % 2 != 0 }
let publisher1 = Just("hello") let publisher2 = Just("world") let mergedPublisher = Publishers.Merge(publisher1, publisher2)
import UIKit import Combine class ViewController: UIViewController { @IBOutlet weak var textField: UITextField! var cancellables = Set<AnyCancellable>() override func viewDidLoad() { super.viewDidLoad() // 创建一个订阅者,打印出文本输入的内容 let subscriber = Subscribers.Assign(object: self.textField, keyPath: \.text) // 订阅文本输入框的文本变化事件 self.textField.textPublisher(for: .editingChanged) .map { $0.text ?? "" } .subscribe(subscriber) .store(in: &cancellables) } } extension UITextField { func textPublisher() -> AnyPublisher<String, Never> { NotificationCenter.default .publisher(for: UITextField.textDidChangeNotification, object: self) .map {($0.object as? UITextField)?.text ?? ""} .eraseToAnyPublisher() } }
import Combine let subject = PassthroughSubject<String, Never>() // 创建PassthroughSubject // 订阅 let subscription = subject.sink(receiveCompletion: { _ in print("receiveCompletion") }, receiveValue: { value in print(value) }) // 发送数据 subject.send("hello") // 中途取消订阅 subscription.cancel() // 后面发送的数据都会失败 subject.send("world") subject.send(completion: .finished) /* 输出: hello */
import UIKit import Combine let dataPublisher = URLSession.shared.dataTaskPublisher(for: URL(string: "https://louyu.cc")!) let cancellableSink = dataPublisher.sink { completion in switch completion { case .finished: break case .failure(let error): print("error: \(error)") break } } receiveValue: { value in print("received \(value)") } cancellableSink.cancel() //取消网络请求