swift - mixLatest 在 Just 与 Future 中具有不同的行为

标签 swift combine

Combine 中有(除其他外)这两个发布商:

let just = Just("Just")
let future = Future<String, Never>({ (promise) in
    DispatchQueue.main.async {
        promise(.success("Future"))
    }
})

当将这两个放入 combineLatest 发布者中时,会有不同的输出,如下所示

just.combineLatest([1,2,3].publisher).sink { (value) in
    print(value)
}.store(in: &bin)
/* prints
("Just", 1)
("Just", 2)
("Just", 3)
*/

future.combineLatest([1,2,3].publisher).sink { (value) in
    print(value)
}.store(in: &bin)
/* prints:
("Future", 3)
*/

是否有任何方法可以修改(例如运算符(operator))Future 发布商,使其表现得像Just 发布商?

最佳答案

Future当您调用 combineLatest 时,行为没有什么不同在上面。由于您在 Future 中添加的异步调度,您的示例存在缺陷。 .

combineLatest仅当其所有上游都发出值时才发出值。因此,如果您添加 DispatchQueue.main.async在你打电话之前promise在你的Future里面,您将延迟 Future 中的发射。正因为如此,Future将晚于 Array.publisher 发出因此,您只会看到 combineLatest 的 1 个(有时是 0 个,具体取决于主线程上的下一个运行循环的执行时间)输出。 .

一旦删除异步调用,您就会看到 Future 的相同输出和Just .

var subscriptions = Set<AnyCancellable>()

let just = Just("Just")
let future = Future<String, Never> { promise in
    promise(.success("Future"))
}

just.combineLatest([1,2,3].publisher).sink { (value) in
    print(value)
}.store(in: &subscriptions)

future.combineLatest([1,2,3].publisher).sink { (value) in
    print(value)
}.store(in: &subscriptions)

关于swift - mixLatest 在 Just 与 Future 中具有不同的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64103509/

相关文章:

ios - 合并CombineLatest不等待上一个操作触发

ios - SwiftUI:在 View 之间传递 ObservableObject 时,表达式类型在没有更多上下文的情况下不明确

ios - 无法从 Observable 对象中提取数据

ios - 从 UTC-5 时区日期和时间 iPhone 应用程序获取当前 iPhone 设备时区日期和时间?

适用于hidesBottomBarWhenPushed的iOS自定义动画

ios - 如何在 iOS 中以编程方式切换到 EarSpeaker?

swift - 在 swift 中使用 WebRTC 进行 iOS 屏幕共享(使用 ReplayKit)

ios - 在 Swift 中添加对指定闭包的弱引用?

swift - Swift Combine PassThroughSubject 发出的意外事件