我在 ViewModel 中有一个函数,它从网络文件中获取一些数据作为 Single。在 viewModel 中,我使用 map 将其转换为不同的模型并将其返回给 ViewController。此映射/转换完成后,我想更新 ViewModel 中的 BehaviorRelay 对象,以告知其订阅者下载已完成。我无法更新此 BehaviorRelay 对象。
我试图在函数中添加一些代码,但在 return 语句中出现错误。
var showLoading = BehaviorRelay<Bool>(value: true)
func getPropertyList(city cityID: String) -> Single<[Property]> {
return propertyListApi.getPropertyList(city: cityID).map({ [weak self] propertInfo -> [Property] in
propertInfo.map({
return Property(name: $0.name, type: "Property Type: " + $0.type, lowestPricePerNight: "", overallRatingPercentage: "Rating: " + String($0.overallRating.overall ?? 0), image: self?.getImageURL(images: $0.images))
})
})
}
我想更新 getPropertyList 函数中的 showLoading 让 ViewController 知道加载完成。
最佳答案
您可以通过将您的 showLoading
订阅到结果来做到这一点...还要注意 showLoading
应该是一个 let,而不是一个 var。
let showLoading = BehaviorRelay<Bool>(value: true)
func getPropertyList(city cityID: String) -> Single<[Property]> {
let result = propertyListApi.getPropertyList(city: cityID).map({ [weak self] propertyInfo -> [Property] in
propertyInfo.map({
return Property(name: $0.name, type: "Property Type: " + $0.type, lowestPricePerNight: "", overallRatingPercentage: "Rating: " + String($0.overallRating.overall ?? 0), image: self?.getImageURL(images: $0.images))
})
})
result
.asObservable() // convert your Single to something that can emit multiple values.
.map { _ in false } // when the request emits a value, emit `false`.
.startWith(true) // when the request starts, emit `true`.
.catchErrorJustReturn(false) // if the request fails, emit `false`.
.bind(to: showLoading) // listen to the emissions above and set yourself accordingly.
.disposed(by: disposeBag) // if self is deleted, cancel the subscription.
return result
}
关于ios - 如何知道 ViewModel 中单个 map 的完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57744784/