Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading