2017-06-12 87 views
2

我有我的视图模型的方法“的getProducts”:RxSwift网络状态观察到的

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类做任何修改就可以做什么?

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

谢谢。

回答

2

这是一个使用由RxSwift作者编写的助手类的解决方案RxSwift Examples,名为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) 
+0

我需要导入什么才能在我的observable上调用trackActivity? – Greg

+0

ActivityIndi​​cator的源文件(该链接发布在我的答案中)已经包含方法trackAcyivity作为ObservableConvertibleType扩展的一部分 – Nimble

+0

谢谢,这就是我一直在寻找的。 – Greg