【发布时间】:2020-08-18 20:14:59
【问题描述】:
我正在使用与 Swift5 结合使用;我有一个 CurrentValueSubject,我正在与一个 @Published 字典变量组合。
问题是当当前值被更新时,map 永远不会被调用!这特别是 @Published 变量的问题,因为它适用于未使用 @Published 的其他流。
@Published var userModels: [String: UserModel] = [:]
var chatModels: CurrentValueSubject<[ChatModelFirebase], Never> = CurrentValueSubject([])
chatModels
.combineLatest(userModels.publisher)
.map({ (chatModels, userModels) -> [ChatViewModel] in
print("Hello") // Never gets called! ????
return []
})
.assign(to: \.chatViewModels, on: self)
.store(in: &cancellableSet)
// Update chat model's value, and notice that map never gets called!
chatModels.values = []
没有错误,代码编译运行,但我从来没有得到流更新的结果。 如果我将userModels 更新为CurrentValueSubject,问题将得到解决,但问题是为什么combineLatest(..) 与@Published 中断?
【问题讨论】:
-
它永远不会被调用,因为
userModels是空的,所以userModels.publisher发送0 个值,而combineLatest从不发送一个元组(它至少在等待第一个值) -
@NewDev
combineLatest文档指出,当任何一个发布者发出Subscribes to an additional publisher and publishes a tuple upon receiving output from either publisher.时都会调用它,请参阅 developer.apple.com/documentation/combine/currentvaluesubject。因此,即使userModels为空,对chatModels的任何更新都应该得到反映。 -
是的,但它至少等待每个值的第一个值(否则,它不能形成一个元组)。之后,它在其中一个中发布一个新值,并结合另一个中的最新值
-
另外,请记住,您实际上并没有使用
Published发布者 - 您正在使用字典的Sequence发布者。如果userModels发生变化,这不会将新值发送到您的管道中。如果您想使用Published发布者 - 您应该使用:$userModels