Michael Long
Apr 10, 2024

--

Try this. The nil assignment is needed in order to capture the cancellable

extension Publisher {

func asyncResult() async throws -> Output {

try await withCheckedThrowingContinuation { continuation in

var cancellable: AnyCancellable?

cancellable = self.sink(

receiveCompletion: {

switch $0 {

case .failure(let error):

continuation.resume(throwing: error)

case .finished:

cancellable = nil

}

}, receiveValue: {

continuation.resume(returning: $0)

}

)

}

}

}

--

--

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

Responses (1)