将 AnyPublisher 进行链式操作的典型方式是使用 Combine 操作符,例如 flatMap。
class MyService {
func getUserList() -> AnyPublisher<[User], Error> {
....
}
func getPostList(user: User) -> AnyPublisher<[Post], Error> {
...
}
}
class ViewModel: ObserableObject {
let service = MyService()
@published var post: [Post] = []
func fetchAllPostFromLastUser() {
service.getUserList().flatMap { [weak self] users in
if let user = users.last {
return self.service.getPosts(user: user)
} else {
return Fail(error:APIError.emptyUsers).eraseToAnyPublisher()
}
}
.sink { result in
}
}
}
有没有更优雅的方式使用async/await,使得代码可以像下面这样简洁
class ViewModel: ObserableObject {
let service = MyService()
@published var post: [Post] = []
func fetchAllPostFromLastUser() {
let users = await service.getUserList().somethingMagicToConvertPublisherToAsync()
let posts = await service.getPostList(user: user.first).somethingMagicToConvertPublisherToAsync()
}
}