使用Combine,你怎么能用nil-coalescing 进行flatMap

sol*_*ell 0 reactive-programming ios swift combine

我有一个发布可选输出类型的发布者。flatMap如果输出不是nil,我需要到一个新的发布者,如果是,则回退到一个空的发布者nil

例如,类似于:

[1, nil, 5].publisher // Generic parameter 'T' could not be inferred
    .flatMap {
        $0?.someNewPublisher ?? Empty(completeImmediately: false)
    }
Run Code Online (Sandbox Code Playgroud)
[1, nil, 5].publisher
    .map {
        $0?.someNewPublisher
    }
    .replaceNil(with: Empty(completeImmediately: false)) // Generic parameter 'Failure' could not be inferred
    .flatMap { $0 }

Run Code Online (Sandbox Code Playgroud)

我想知道我是否试图以错误的方式解决这个问题。需要明确的是,nil在映射之前过滤并不能解决我的问题,因为这不会用一个空的发布者替换当前的发布者(我将继续接收我不应该再接收的元素)。

Lot*_*lla 5

有一种Optional.Publisher类型。如果您调用.publisher一个可选值,您将获得一个生成包装类型或立即完成的发布者。

optionalValue.publisher.flatMap(\.someNewPublisher)

编辑:

由于此功能受 iOS14+ 保护,因此这里有一个扩展,它创建相同的功能,但作为一个函数,这样它就不会与publisher var.

请注意,我没有设置completeImmediately false,它会自动设置为true,并且将其设置为false意味着发布者永远不会完成。

extension Optional {
    func publisher() -> AnyPublisher<Wrapped, Never> {
        switch self {
        case let .some(wrapped):
            return Just(wrapped).eraseToAnyPublisher()
        case .none:
            return Empty().eraseToAnyPublisher()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)