Combine 入門-Publisher

Zhi-Hong Lin
Oct 19, 2021

--

Combine 是 FRP (Functional Reactive Programming) 在 Swift 中的一個實現,有三個核心概念,分別為發布者(Publisher)、訂閱者(Subscriber)、操作者(Operator),此篇會先介紹較為常用的 Publisher

發布者(Publisher):負責發送數據

訂閱者(Subscriber):負責訂閱、接收數據

操作者(Operator):負責在 Publisher 和 Subscriber 之間進行數據的轉換

如果把 pipline 想成一個飲料生產線,Publisher 就表示茶,Subscriber 就表示成品飲料,Operator 就表示中間處理過程。

Foundation 中的 Publisher

Foundation 對一些常用的操作擴充了基於 Publisher 的 API,我們在開發中可以直接進行調用,以下就逐個列出這些 API 的具體用法。

Sequence

凡是實現了Sequence協議的物件,都可以呼叫.publisher來自動建立一個publisher,然後就可以使用 Combine 中的所有功能。最常用的類型為ArraySetDictionayString

URLSession

Notification

系統通知

自定義通知

KVO

任何 NSObject 一旦被 KVO 監聽,則可以成為一個 Publisher

開發中常用的 KVO Publisher

Timer

TimerPublisher 實現了 ConnectablePublisher協議,因此它可以調用 .autoconnect().connect()

autoconnect():subscriber 可以馬上接收到定時器發送的元素

connect():調用 connect() 方法之前,subscriber 不會接收到定時器發送的元素

@Published

是一個(Property Wrapper),可以為任何一個屬性生成其對應類型的 Publisher,這個 Publisher 會在屬性值發生變化時發送消息。用 @Published 修飾的屬性通過 $屬性名即可得到該屬性對應的 Publisher

在 class 內使用

在 protocol 使用

Subject

一種特殊的 Publisher,也能當作 Subscriber,Subject 的最大特點就是可以手動發送數據,透過調用send() 方法,有兩種內建的 Subject,分別為 PassthroughSubjectCurrentValueSubject,區別在於是否會對收到的數據進行保留

PassthroughSubject

PassthroughSubject 不會對接收到的數據進行保留,不需要初始值。

用途:比如按鈕點擊等事件

CurrentValueSubject

CurrentValueSubject 會保留一個最後的數據,並需要初始值,當 CurrentValueSubject 被訂閱時,訂閱者馬上會收到當前值

用途:表示狀態,比如 switch 狀態關閉、打開

AnyPublisher

AnyPublisher 是 Publisher 的具體實現,多用於函數返回 Publisher 的實體,透過調用 eraseToAnyPublisher() 可以隱藏發布者類型,避免外部使用 send() 發送數據

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response