2017-06-12 88 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