首页 > 解决方案 > Swift Combine:一个发布者消费另一个发布者,如何让两个流都退出

问题描述

我想要一些帮助来理解为什么我的发布者没有通过 combineLatest 运算符发出元素。我有一个发布视频帧的发布者,以及另一个使用这些视频帧并从这些帧中提取人脸的发布者。我现在正在尝试使用 combineLatest 将原始视频帧和转换后的输出合并为一个(我正在使用一些自定义发布者来提取视频帧并转换帧):

let videoPublisher = VideoPublisher //Custom Publisher that outputs CVImageBuffers
.share()

let faceDetectionPublisher = videoPublisher
.detectFaces() // Custom Publisher/subscriber that takes in video frames and outputs an array of VNFaceObservations

let featurePublisher = videoPublisher.combineLatest(faceDetectionPublisher)
.sink(receiveCompletion:{_ in
                print("done")
            }, receiveValue: { (video, faces) in
                print("video", video)
                print("faces", faces)
            })

但是,我没有从 combineLatest 中获得任何活动。经过一些调试,我认为问题在于 videoPublisher 中的所有 videoFrames 都已发布,然后才能成功通过 faceDetectionPublisher。如果我将打印语句附加到 videoPublisher 和 faceDetectionPublisher 的末尾,我可以看到前者的输出,但看不到后者的输出。我已经阅读了组合和其他技术(例如多播),但还没有找到可行的解决方案。我喜欢任何关于如何更好地理解框架的综合专业知识或指导!

标签: swiftpublishercombinecombinelatest

解决方案


在每个来源发出至少一个值之前,您的 combineLatest 不会发出任何东西。由于detectFaces()从不排放,因此您的链条正在停止。您的detectFaces()操作员有问题,或者可能没有要检测的面孔,在这种情况下,您的逻辑是错误的。

如果是后一种情况,则使用prepend结果为detectFaces()管道播种一些默认值(可能是一个空数组?)


推荐阅读