Combine 入門-Subscriber

Zhi-Hong Lin
Oct 20, 2021

--

如果沒有任何訂閱請求,Publisher 不會主動發布任何數據。所以說Subscriber 負責向 Publisher 請求數據並接收數據,內建的 Subscriber 分別是 sink()assign(to:on:)

Sink

sink() 在閉包中處理收到的數據或者 completion 事件。receiveCompletion 用於接收完成事件,包括.finished.failurereceiveValue用於接收數據

注:處理 completion 事件的 receiveCompletion 閉包是 optional 的,這個閉包會在接收到 Publisher 終止的消息後調用

Assign

assign(to:on:) 將接收到的值通過 KeyPath 設置到指定的 class 上(不支持Struct/enum)。

注:要調用 assign(to:on:) ,Publisher 的 Failure 只能是 Never

綁定到 UI 元件

綁定到 Model

Retain Cycle

調用 sink()assign(to:on:) 時,可能會造成 retain cycle,以下範例製造出 retain cycle 的情況

Sink Retain Cycle Resolution

透過 weak 或 unowned 打破 retain cycle

$subscriber
.sink { [weak self] value in
guard
let self = self else { return }
self.value = value
}

Assign Retain Cycle Resolution

透過調用 assignNoRetain() 解決 retain cycle

$subscriber
.assignNoRetain(to: \.value, on: self)
.store(in: &cancellables)

assignNoRetain() 參考來源

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