【问题标题】:How to know completion of map on a Single in ViewModel?如何知道 ViewModel 中单个地图的完成情况?
【发布时间】:2019-09-01 09:27:29
【问题描述】:

我在 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 知道加载完成。

【问题讨论】:

    标签: ios swift rx-swift


    【解决方案1】:

    您可以通过将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
    }
    

    【讨论】:

    • 很棒的丹尼尔,它非常适合我。只是补充一下,我无法将 showLoader 属性设置为 let,因为我必须将它添加到我的协议中作为 get 属性。
    • 那就只写get 而不是get set
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    相关资源
    最近更新 更多