RxSwift 网络状态可观察

RxSwift network status observable

我的视图模型中有一个方法 'getProducts':

struct MyViewModel {
    func getProducts(categoryId: Int) -> Observable<[Product]> {
        return api.products(categoryId: categoryId)
    }
    var isRunning: Observable <Bool> = {
        ...
    }
}

api.products 是一个私有变量,它在后台使用 URLSession rx 扩展名:session.rx.data(...)

我想在我的视图模型中有一些 isRunning 观察者,我可以订阅它以了解它是否在执行网络请求。

这是我可以在不对我的 api class 做任何修改的情况下做的事情吗?

我是响应式编程的新手,所以任何帮助将不胜感激。

谢谢。

这是一个解决方案,它使用了由 RxSwift 作者在 RxSwift Examples 中编写的助手 class,名为 ActivityIndicator

思路很简单

struct MyViewModel {
    /// 1. Create an instance of ActivityIndicator in your viewModel. You can make it private
    private let activityIndicator = ActivityIndicator()

    /// 2. Make public access to observable part of ActivityIndicator as you already mentioned in your question
    var isRunning: Observable<Bool> {
        return activityIndicator.asObservable()
    }

    func getProducts(categoryId: Int) -> Observable<[Product]> {
        return api.products(categoryId: categoryId)
            .trackActivity(activityIndicator) /// 3. Call trackActivity method in your observable network call
    }
}

在相关 ViewController 中,您现在可以订阅 isRunning 属性。例如:

    viewModel.isLoading.subscribe(onNext: { loading in
        print(loading)
    }).disposed(by: bag)