Pankaj Gaikar
Pankaj Gaikar

Reputation: 2483

How does Combine work inside try-catch block?

I am trying to make a try-catch block with combine so I can execute certain function and re-execute main block again. I am doing something like this -

return urlSession.dataTaskPublisher(for: request)
    .tryMap(verifyAPIResponse)
    .tryCatch { (error) -> AnyPublisher<(data: Data, response: URLResponse), URLError> in
        self.apiCallOne()
            .tryMap(\.apiResponse)
            .tryMap({ (response) in
            })
        return self.urlSession.dataTaskPublisher(for: request) //<<- DOES this execute after refreshToken or executes in parallel?
    }
    .tryMap(parseJson)
    .receive(on: RunLoop.main)
    .eraseToAnyPublisher()

So my main concern here is -

  1. Does the apiCallOne happen before it returns self.urlSession.dataTaskPublisher(for: request) or
  2. Does the API call apiCallOne execute in background and self.urlSession.dataTaskPublisher(for: request) will be returned immediately? If so, I can I return after completion of apiCallOne?

Any pointers/help would be great.

Upvotes: 0

Views: 371

Answers (1)

Daniel T.
Daniel T.

Reputation: 33967

The functions in the tryCatch closure execute in sequence just like any normal code. First apiCallOne() executes, then when it returns tryMap(\.apiResponse) executes then tryMap({ response in }) executes then the dataTaskPublisher(for:) executes and the value from it is returned.

Keep in mind that dataTaskPublisher(for:) returns its Publisher immediately but starts doing work in the background. That work emits a value through the Publisher at some later time.

I expect that, based on the name of the function, apiCallOne() also returns immediately but starts doing work in the background and emits a value at some later time. The two tryMaps also return immediately but emit values when the Publisher they are called on emit a value.

All of this has the effect of the apiCallOne()s work happening at the same time as the dataTaskPublisher(for:)s work.

Upvotes: 1

Related Questions