什么是PassthroughSubject&CurrentValueSubject [英] What is PassthroughSubject & CurrentValueSubject

查看:166
本文介绍了什么是PassthroughSubject&CurrentValueSubject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰巧看到了Apple的新Combine框架,在那里我看到了两件事

I happen to look into Apple's new Combine framework, where I see two things

PassthroughSubject<字符串,失败>

CurrentValueSubject<字符串,失败>

有人可以向我解释什么是&使用它们吗?

Can someone explain to me what is meaning & use of them?

推荐答案

PassthroughSubject CurrentValueSubject 都是符合 Subject 协议的发布者这意味着您可以调用它们上的 send 随意向下游推送新值.

Both PassthroughSubject and CurrentValueSubject are publishers that conform to the Subject protocol which means you can call send on them to push new values downstream at will.

主要区别在于, CurrentValueSubject 具有状态感(当前值),而 PassthroughSubject 只是将值直接中继给其订户,而无需记住当前"值:

The main difference is that CurrentValueSubject has a sense of state (current value) and PassthroughSubject simply relays values directly to its subscribers without remembering the "current" value:

var current = CurrentValueSubject<Int, Never>(10)
var passthrough = PassthroughSubject<Int, Never>()

current.send(1)
passthrough.send(1)

current.sink(receiveValue: { print($0) })
passthrough.sink(receiveValue: { print($0) })

您会看到 current.sink 被立即用 1 调用.未调用 passthrough.sink ,因为它没有当前值.订阅者只会在您订阅后发出的值时调用接收器.

You'd see that the current.sink is called immediately with 1. The passthrough.sink is not called because it has no current value. The sink will only be called for values that are emitted after you subscribe.

请注意,您还可以使用其 value 属性获取并设置 CurrentValueSubject 的当前值:

Note that you can also get and set the current value of a CurrentValueSubject using its value property:

current.value // 1
current.value = 5 // equivalent to current.send(5)

这对于直通主题是不可能的.

This isn't possible for a passthrough subject.

这篇关于什么是PassthroughSubject&amp;CurrentValueSubject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆