swiftcombine

How to convert AnyPublisher<Void, Error> return value to async throws?


I have a protocol method:

func do() async throws

In the implementation I must call one function something() returning AnyPublisher<Void, Error>:

func something() -> AnyPublisher<Void, Error>

How should my do() body look to basically convert AnyPublisher<Void, Error> return value to async throws?

func do() async throws
{
    try await ??? something()
}

Solution

  • You can turn a Publisher into an AsyncSequence using the values property.

    If you only care about the next single value that gets published, you can just make an async iterator and call next:

    let publishedValues = something().values
    var iterator = publishedValues.makeAsyncIterator()
    try await iterator.next()
    print("Waiting Done!")
    

    This will wait until the publisher publishes its next value, or the completion of the publisher, whichever comes first.

    If you care about more than one value, you can use a for loop:

    for try await _ in publishedValues {
        // this gets run for each value that is published
    }
    

    This loop will end when the publisher completes.