如何将 AnyPublisher<Void, Error> 返回值转换为异步抛出?

问题描述 投票:0回答:1

我有一个协议方法:

func do() async throws

在实现中我必须调用一个函数

something()
返回
AnyPublisher<Void, Error>
:

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

我的

do()
身体应该如何基本上将
AnyPublisher<Void, Error>
返回值转换为
async throws

func do() async throws
{
    try await ??? something()
}
ios swift combine
1个回答
0
投票

您可以使用

Publisher
 属性将 AsyncSequence
 转换为 
values

如果您只关心发布的下一个单个值,您可以创建一个异步迭代器并调用

next

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

这将等到发布者发布其下一个值,或发布者完成,以先到者为准。

如果您关心多个值,可以使用

for
循环:

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

当发布者完成时,此循环将结束。

© www.soinside.com 2019 - 2024. All rights reserved.