本文首发于 Ficow Shen's Blog,原文地址: Combine 框架,从0到1 —— 5.Combine 中的 Subjects

内容概览

  • 前言
  • PassthroughSubject
  • CurrentValueSubject
  • Subject 作为订阅者
  • 常见用法
  • 总结

前言

正所谓,工欲善其事,必先利其器。在开始使用 Combine 进行响应式编程之前,建议您先了解 Combine 为您提供的各种发布者(Publishers)、操作符(Operators)、订阅者(Subscribers)。

Subject 是一类比较特殊的发布者,因为它同时也是订阅者。Combine 提供了两类 SubjectPassthroughSubjectCurrentValueSubject

如果您想了解更多 Publishers 的用法和注意事项,可以阅读:Combine 框架,从0到1 —— 5.Combine 提供的发布者(Publishers)

PassthroughSubject

官网文档

PassthroughSubject 可以向下游订阅者广播发送元素。使用 PassthroughSubject 可以很好地适应命令式编程场景。

如果没有订阅者,或者需求为0,PassthroughSubject 就会丢弃元素。

示例代码:

final class SubjectsDemo {

    private var cancellable: AnyCancellable?
private let passThroughtSubject = PassthroughSubject<Int, Never>() func passThroughtSubjectDemo() {
cancellable = passThroughtSubject
.sink {
print(#function, $0)
}
passThroughtSubject.send(1)
passThroughtSubject.send(2)
passThroughtSubject.send(3)
}
}

输出内容:

passThroughtSubjectDemo() 1

passThroughtSubjectDemo() 2

passThroughtSubjectDemo() 3

CurrentValueSubject

官网文档

CurrentValueSubject 包装一个值,当这个值发生改变时,它会发布一个新的元素给下游订阅者。

CurrentValueSubject 需要在初始化时提供一个默认值,您可以通过 value 属性访问这个值。在调用 send(_:) 方法发送元素后,这个缓存值也会被更新。

示例代码:

final class SubjectsDemo {

    private var cancellable: AnyCancellable?
private let currentValueSubject = CurrentValueSubject<Int, Never>(1) func currentValueSubjectDemo() {
cancellable = currentValueSubject
.sink { [unowned self] in
print(#function, $0)
print("Value of currentValueSubject:", self.currentValueSubject.value)
}
currentValueSubject.send(2)
currentValueSubject.send(3)
}
}

输出内容:

currentValueSubjectDemo() 1

Value of currentValueSubject: 1

currentValueSubjectDemo() 2

Value of currentValueSubject: 2

currentValueSubjectDemo() 3

Value of currentValueSubject: 3

Subject 作为订阅者

示例代码:

final class SubjectsDemo {

    private var cancellable1: AnyCancellable?
private var cancellable2: AnyCancellable? private let optionalCurrentValueSubject = CurrentValueSubject<Int?, Never>(nil) private func subjectSubscriber() {
cancellable1 = optionalCurrentValueSubject
.sink {
print(#function, $0)
}
cancellable2 = [1, 2, 3].publisher
.subscribe(optionalCurrentValueSubject)
}
}

optionalCurrentValueSubject 可以作为一个订阅者去订阅序列发布者 [1, 2, 3].publisher 发送的元素。

输出内容:

subjectSubscriber() nil

subjectSubscriber() Optional(1)

subjectSubscriber() Optional(2)

subjectSubscriber() Optional(3)

常见用法

在使用 Subject 时,我们往往不会将其暴露给调用方。这时候,可以使用 eraseToAnyPublisher 操作符来隐藏内部的 Subject

示例代码:

    struct Model {
let id: UUID
let name: String
} final class ViewModel {
private let modelSubject = CurrentValueSubject<Model?, Never>(nil)
var modelPublisher: AnyPublisher<Model?, Never> {
return modelSubject.eraseToAnyPublisher()
} func updateName(_ name: String) {
modelSubject.send(.init(id: UUID(), name: name))
}
}

外部调用者无法直接操控 ViewModel 内部的 Subject,这样可以让 ViewModel 更好地面对将来可能的改动。

外部调用者只需要知道 modelPublisherAnyPublisher<Model?, Never> 类型的发布者即可,无论内部采用了 CurrentValueSubject 还是 PassthroughSubject 甚至是其他的发布者。

总结

相比于其他的发布者来说, Subject 是比较容易理解的,而且也是最常用到的。

只可惜,对比 Rx 提供的 Subject,Combine 中的 Subject 无法设置缓冲的大小。也许某天苹果会对此做出调整吧~

Combine 框架,从0到1 —— 5.Combine 中的 Subjects的更多相关文章

  1. Combine 框架,从0到1 —— 1.核心概念

      本文首发于 Ficow Shen's Blog,原文地址: Combine 框架,从0到1 -- 1.核心概念.     内容概览 前言 核心概念 RxSwift Combine 总结 参考内容 ...

  2. Combine 框架,从0到1 —— 2.通过 ConnectablePublisher 控制何时发布

      本文首发于 Ficow Shen's Blog,原文地址: Combine 框架,从0到1 -- 2.通过 ConnectablePublisher 控制何时发布.   内容概览 前言 使用 ma ...

  3. Combine 框架,从0到1 —— 3.使用 Subscriber 控制发布速度

      本文首发于 Ficow Shen's Blog,原文地址: Combine 框架,从0到1 -- 3.使用 Subscriber 控制发布速度.   内容概览 前言 在发布者生产元素时消耗它们 使 ...

  4. Combine 框架,从0到1 —— 4.在 Combine 中使用通知

      本文首发于 Ficow Shen's Blog,原文地址: Combine 框架,从0到1 -- 4.在 Combine 中使用通知.   内容概览 前言 让通知处理代码使用 Combine 总结 ...

  5. Combine 框架,从0到1 —— 4.在 Combine 中使用计时器

    本文首发于 Ficow Shen's Blog,原文地址: Combine 框架,从0到1 -- 4.在 Combine 中使用计时器. 内容概览 前言 使用计时器执行周期性的工作 将计时器转换为计时 ...

  6. Combine 框架,从0到1 —— 4.在 Combine 中使用 KVO

      本文首发于 Ficow Shen's Blog,原文地址: Combine 框架,从0到1 -- 4.在 Combine 中使用 KVO.   内容概览 前言 用 KVO 监控改动 将 KVO 代 ...

  7. Combine 框架,从0到1 —— 4.在 Combine 中执行异步代码

    本文首发于 Ficow Shen's Blog,原文地址: Combine 框架,从0到1 -- 4.在 Combine 中执行异步代码. 内容概览 前言 用 Future 取代回调闭包 用输出类型( ...

  8. Combine 框架,从0到1 —— 5.Combine 提供的发布者(Publishers)

    本文首发于 Ficow Shen's Blog,原文地址: Combine 框架,从0到1 -- 5.Combine 提供的发布者(Publishers). 内容概览 前言 Just Future D ...

  9. Combine 框架,从0到1 —— 5.Combine 常用操作符

    本文首发于 Ficow Shen's Blog,原文地址: Combine 框架,从0到1 -- 5.Combine 常用操作符. 内容概览 前言 print breakpoint handleEve ...

随机推荐

  1. Windows & Linux 安装使用 Vim 编辑器 3分钟入门 - 精简归纳

    Windows & Linux 安装使用 Vim 编辑器 3分钟入门 - 精简归纳 JERRY_Z. ~ 2020 / 8 / 25 转载请注明出处! 目录 Windows & Lin ...

  2. vue混入mixins时注意的问题

    mixin.js - 方式一:导出对象 const mixin = { mounted () { console.log('fffffffffffff') }, methods: { } } expo ...

  3. Mysql安装错误

    [问题一]在安装mysql时遇到以下错误 执行./mysqld --initialize 后 ./bin/mysqld: error while loading shared libraries: l ...

  4. nginx配置过程中出现的问题

    在安装nginx时我们先创建用户useradd -s /sbin/nologin -M nginx 不然会报nginx: [emerg] getpwnam("nginx") fai ...

  5. Selenium执行js脚本

    如何使用Selenium来执行Javascript脚本呢 Selenium中提供了一个方法:execute_script 来执行js脚本 return 可以返回js的返回结果 execute_scri ...

  6. BM算法学习

    根据阮一峰大大的文章实现,不过没实现“搜索词中的上一次出现位置”(我直接实时查找,显然应该预处理): 文章:http://www.ruanyifeng.com/blog/2013/05/boyer-m ...

  7. CSDN自定义栏目代码

    今天终于发现了csdn可以操作的地方,有个自定义栏目的地方可以贴HTML代码(只允许最多一个自定义栏目),不能用JS插件 有点难受,就贴了下自己的微信,并且可以直接点击图片发起会话 以下是我的代码,可 ...

  8. 一文看懂 YAML

    前言 YAML 并不是一种新奇的语言,YAML 首次发表于 2001 年,距离现在已经过去差不多 20 个年头.YAML 虽然不如 JSON.XML 之类的语言流行,应用也没有那么广泛,但是 YAML ...

  9. ARM函数调用总结

    ARM架构寄存器介绍 ARM架构下处理器有7种工作模式: 1. USR模式:正常用户模式,在USR模式下进程正常执行 2. FIQ模式(Fast Interrupt Request):处理快速中断模式 ...

  10. Oracle数据库添加约束

    主键约束(两个特性)1:主键必须写2:主键不可重复 create table stu01( sid varchar(100), sname varchar2(100) --constraint PK_ ...