[SOLVED] Swift: Return publisher after another publisher is done


I’m very new to the concept Publishers and I’m creating a networking service using dataTaskPublisher on URLSession. There is a case for refreshing token and I have a refreshToken() method which returns AnyPublisher<Bool, Never>:

    func refreshToken() -> AnyPublisher<Bool, Never> {
        var disposable = Set<AnyCancellable>()
        do {
            let request = URLRequest(url: URL(string: "refresh_token_url")!)
            URLSession.shared.dataTaskPublisher(for: request).sink { finished in
                /// Compiler error: Cannot convert value of type 'AnyPublisher<Bool, Never>' to closure result type 'Void'
                return Just(false).eraseToAnyPublisher()
            } receiveValue: { _ in
                /// What should I return here?
                return Just(true).eraseToAnyPublisher()
            }.store(in: &disposable)

        } catch {
            return Just(false).eraseToAnyPublisher()

Compiler complains for both of Just().eraseToAnyPublisher(). I don’t know how and where should return Just(false).eraseToAnyPublisher() based on success or failure of this refresh token call.


It is the caller of this function who will need to store the token (AnyCancellable) so there is no need for the sink (which is the reason for the error you are seeing). There is no need to wrap a publisher in a do-try-catch block.

This approach would compile:

func refreshToken() -> AnyPublisher<Bool, Never> {
    let request = URLRequest(url: URL(string: "refresh_token_url")!)
    return URLSession.shared
        .dataTaskPublisher(for: request)
        .map { _ in true }
        .replaceError(with: false)

Though it does not make much sense for a method called refreshToken to return a Bool. You should decode the response, extract the token and publish that (AnyPublisher<String, Error>).

Answered By – LuLuGaGa

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *