2017-08-23 210 views
0

我在viewWillAppear中寫了一個訂閱。
但它也運行在第一次啓動應用程序。
當我推到另一個viewcontroller,我使用dispose()。
然後我回到第一個視圖控制器,我在viewWillAppear的訂閱func不運行。
我的rx訂閱有什麼問題?爲什麼RxSwift訂閱只在第一次啓動viewWillAppear運行一次?

var listSubscribe:Disposable? 

override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(animated) 

    listSubscribe = chatrooms.notifySubject.subscribe({ json in 
     print("*1") //just print once in first launch 
     self.loadContents() 
    }) 
} 

override func viewWillDisappear(_ animated: Bool) { 
    super.viewWillDisappear(animated) 

    let controllers = tabBarController?.navigationController?.viewControllers 
    if (controllers?.count)! > 1 { 
     listSubscribe?.dispose() 
    } 
} 

回答

0

RxSwift文件說"Note that you usually do not want to manually call dispose; this is only an educational example. Calling dispose manually is usually a bad code smell."

通常情況下,你應該做這樣的事情 -

let disposeBag = DisposeBag() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     whatever.subscribe(onNext: { event in 
     // do stuff 
     }).disposed(by: self.disposeBag) 

    } 

至於你的問題,我相信你不需要重新訂閱因爲你訂閱將保持活躍狀態​​,'notifySubject'會在您有任何更新時向您發送更新。

0

也許你可以得到一些被動的執行viewWillAppear和類似的功能?而忘記了手動一次性處理...例如您UIViewControllerinit將包含這樣的事情:

rx.driverViewState() 
    .asObservable() 
    .filter({ $0 == .willAppear }) 
    .take(1) // if you need only first viewWillAppear call 
    .flatMapLatest({ _ in 
     // Do what you need 
    }) 

driverViewState實現:

public extension UIViewController { 

    public enum ViewState { 
     case unknown, didAppear, didDisappear, willAppear, willDisappear 
    } 
} 

public extension Reactive where Base: UIViewController { 

    private typealias _StateSelector = (Selector, UIViewController.ViewState) 
    private typealias _State = UIViewController.ViewState 

    private func observableAppearance(_ selector: Selector, state: _State) -> Observable<UIViewController.ViewState> { 
     return (base as UIViewController).rx 
      .methodInvoked(selector) 
      .map { _ in state } 
    } 

    func driverViewState() -> Driver<UIViewController.ViewState> { 
     let statesAndSelectors: [_StateSelector] = [ 
      (#selector(UIViewController.viewDidAppear(_:)), .didAppear), 
      (#selector(UIViewController.viewDidDisappear(_:)), .didDisappear), 
      (#selector(UIViewController.viewWillAppear(_:)), .willAppear), 
      (#selector(UIViewController.viewWillDisappear(_:)), .willDisappear) 
     ] 
     let observables = statesAndSelectors 
      .map({ observableAppearance($0.0, state: $0.1) }) 
     return Observable 
      .from(observables) 
      .merge() 
      .asDriver(onErrorJustReturn: UIViewController.ViewState.unknown) 
      .startWith(UIViewController.ViewState.unknown) 
      .distinctUntilChanged() 
    } 
} 
相關問題