Combine 操作符六

  • Swift Combine

  • map/mapError

map 将收到的值按照给定的 closure 转换为其他值,mapError 则将错误转换为另外一种错误类型。

func map<T>(_ transform: (Output) -> T) -> Publishers.Just<T>

image

replaceNil

replaceNil 将收到的 nil 转换为给定的值。

func replaceNil<T>(with output: T) -> Publishers.Map<Self, T> where Self.Output == T?
scan

scan 将收到的值与当前的值(第一次使用 initialResult )按照给定的 closure 进行转换。

func scan<T>(_ initialResult: T, _ nextPartialResult: @escaping (T, Self.Output) -> T) -> Publishers.Scan<Self, T>

image

setFailureType

setFailureType 强制将上游 Publisher 的错误类型设置为指定类型。这个方法并不是进行错误类型的转换,因为它并没有让我们提供一个 closure,实际上只是为了让不同的 Publisher 的错误类型进行统一,因而这个 Publisher 实际上是不应该发生错误的。

func scan<T>(_ initialResult: T, _ nextPartialResult: @escaping (T, Self.Output) -> T) -> Publishers.Scan<Self, T>

filter

filter 只会让满足条件的值通过。

func filter(_ isIncluded: @escaping (Self.Output) -> Bool) -> Publishers.Filter<Self>

image

compactMap

compactMap 和 map 的功能类似,只是会自动过滤掉空的元素。

func compactMap<T>(_ transform: @escaping (Self.Output) -> T?) -> Publishers.CompactMap<Self, T>
removeDuplicates

removeDuplicates 会跳过在之前已经出现过的值。

func removeDuplicates(by predicate: @escaping (Self.Output, Self.Output) -> Bool) -> Publishers.Remo

image

replaceEmpty/replaceError

如果上游 Publisher 是个空的数据流,replaceEmpty 会发送指定的值,然后正常结束。

如果上游 Publisher 因错误而终止,replaceError 会发送指定的值,然后正常结束。

func replaceEmpty(with output: Self.Output) -> Publishers.ReplaceEmpty<Self>
func replaceError(with output: Self.Output) -> Publishers.ReplaceError<Self>

image

drop

drop` 会一致丢弃收到的值,直到给定的条件得到满足,然后后面的值会正常发送。

func drop(while predicate: @escaping (Self.Output) -> Bool) -> Publishers.DropWhile<Self>

image

allSatisfy

allSatisfy 会返回一个布尔值来表示所有收到的值是否满足给定的条件。需要说明的是,一旦收到的值不满足条件, allSatisfy 会立即发送 false 并且正常结束,而如果收到的值满足条件,会一直等到收到上游的 Publisher 发出正常结束的消息之后才发送 true 并且正常结束。

func allSatisfy(_ predicate: @escaping (Self.Output) -> Bool) -> Publishers.AllSatisfy<Self>

image

contains

contains 会返回一个布尔值来表示收到的值是否包含满足给定的条件的值。需要说明的是,一旦收到的值满足条件, contains 会立即发送 true 并且正常结束,而如果收到的值不满足条件,会一直等到收到上游的 Publisher 发出正常结束的消息之后才发送 false 并且正常结束。

func contains(_ output: Self.Output) -> Publishers.Contains<Self>

![image](/uploads/b04c483e5c3e3558d6868d367f29584b/image.png)

subscribe(on:)/receiveOn(on:)

在前面的介绍中,我们都没有提及到线程的管理。一种非常常见的场景是我们希望耗时的操作在异步执行,操作完成后在主线程发布值更新的消息,以便于我们直接更新到 UI 控件上。在 Combine 中,这是通过 Scheduler 来实现的,Scheduler 定义了什么时候以及怎么去执行操作,例如区分后台线程和主线程。

subscribe(on:) 指定了 Publisher 在某个 Scheduler 执行,而 receiveOn(on:) 指定了 Publisher 在哪个 Scheduler 发出通知。

let ioPerformingPublisher == // Some publisher.

let uiUpdatingSubscriber == // Some subscriber that updates the UI.

ioPerformingPublisher  .subscribe(on: backgroundQueue)  .receiveOn(on: mainQueue)  .subscribe(uiUpdatingSubscriber)

image

猜你喜欢

转载自www.cnblogs.com/liuxiaokun/p/12684260.html