swift 使用发布者链接时处理平面Map中的错误

ebdffaop  于 2022-10-31  发布在  Swift
关注(0)|答案(1)|浏览(119)

我尝试在我的Swift应用程序中使用合并,但在以下代码中出现问题:

//Get it from local storage(realm)
    voucherCodeStorageProvider.fetchVoucherCode(voucherId).flatMap { (code) -> AnyPublisher<String?, Error> in
            if let code = code {
                return Just(code).setFailureType(to: Error.self).eraseToAnyPublisher()
            }
            //If not found in storage, Get it from api
            return self.voucherCodeProvider.fetchVoucherCode(voucherId: voucherId).handleEvents( receiveOutput: { code in
                guard let code = code else { return }
                _ = self.voucherCodeStorageProvider.saveVoucherCode(code, voucherId)
            }).mapError{ $0 as Error }.eraseToAnyPublisher()
        }.eraseToAnyPublisher()

上面的fetchVoucherCode当前正在发布一个错误,现在我想捕获该错误并在代码中执行nil检查后执行的任务。但我无法在此处捕获错误。有人能帮助我如何在flatmap中捕获错误并执行类似上面的操作吗?

42fyovps

42fyovps1#

我在flatmap之前使用了catch。下面是我的工作代码,如果其他人也需要帮助的话:

voucherCodeStorageProvider.fetchVoucherCode(voucherId).catch { _ in
        return self.voucherCodeProvider.fetchVoucherCode(voucherId: voucherId).handleEvents( receiveOutput: { code in
            guard let code = code else { return }
            _ = self.voucherCodeStorageProvider.saveVoucherCode(code, voucherId)
        }).mapError{ $0 as Error }.eraseToAnyPublisher()

    }.flatMap { (code) -> AnyPublisher<String?, Error> in
        return Just(code).setFailureType(to: Error.self).eraseToAnyPublisher()
    }.eraseToAnyPublisher()

相关问题