RxSwift网络状态可观察

时间:2017-06-12 11:00:10

标签: ios swift reactive-programming reactive-cocoa rx-swift

我的视图模型中有一个'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课程进行任何修改,我能做些什么吗?

我是反应式编程的新手,所以任何帮助都会受到赞赏。

感谢。

1 个答案:

答案 0 :(得分:2)

这是一个解决方案,使用由RxSwift Examples中名为ActivityIndicator的RxSwift作者编写的帮助程序类。

想法很简单

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)
相关问题