.tryCatch中的Swift-Combine-同步API执行 [英] Swift - Combine - Synchronous API execution inside .tryCatch

查看:157
本文介绍了.tryCatch中的Swift-Combine-同步API执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决我想捕获该错误的401错误情况,请检查错误是否为401,以及是否为-

I am trying to work around 401 error scenario where I want to catch the error, check if error is 401 and if it is -

  1. 刷新oAuth
  2. 再次执行相同的API.

当前,我正在执行以下操作-

Currently, I am doing something like below -

return urlSession.dataTaskPublisher(for: request)
    .tryMap(checkForAPIError)
    .tryCatch { (error) -> AnyPublisher<(data: serverData, response: URLResponse), URLError> in
        self.fetchoAuthToken()
            .tryMap { (token) in
                // Saves token
            }
            .receive(on: RunLoop.main)
            .subscribe(on: DispatchQueue.main)
            .sink { (completion) in
                 // Completion handling here
            } receiveValue: { (value) in
                print("Received \(value)")
            }
            .store(in: &self.subscription)

        return self.urlSession.dataTaskPublisher(for: request)
    }
    .tryMap(parseJson)
    .retry(3)
    .receive(on: RunLoop.main)
    .eraseToAnyPublisher()

对我来说,当前问题是,尽管API self.fetchoAuthToken()仍在执行中,但block返回了新请求.然后使用旧令牌执行.

我希望 self.fetchoAuthToken同步执行,以便可以在执行后返回,并可以使用新的令牌.任何帮助将不胜感激.

I want the self.fetchoAuthToken execute synchronously so return can be done after it executes and new tokens can be used. Any help would be appreciated.

推荐答案

您需要链接发布者,并从 tryCatch 将链接作为新发布者返回.

You need to chain the publishers, and return the chain as a new publisher from tryCatch.

通常应避免产生副作用,但如果必须-如保存OAuth令牌,请在 .handleEvents 中进行操作,而不要创建 sink 订阅./p>

You should typically avoid side-effects, but if you must - like saving the OAuth token, do that in .handleEvents, instead of creating a sink subscription.

return urlSession.dataTaskPublisher(for: request)
    .tryMap(checkForAPIError)
    .tryCatch { error in
        self.fetchoAuthToken()
            .handleEvents(receiveOutput: { (token) in
                // Saves token
            })
            .flatMap { _ in 
                urlSession.dataTaskPublisher(for: request) 
            }
    }
    .tryMap(parseJson)
    .retry(3)
    .receive(on: RunLoop.main)
    .eraseToAnyPublisher()

这篇关于.tryCatch中的Swift-Combine-同步API执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆