使用RxSwift和MVVM显示活动指示器

时间:2019-01-16 08:44:28

标签: ios swift rx-swift

我有一个分层的体系结构应用程序,在其中我在ViewModel中获取对象数组并将其与ViewController中的tableview绑定。以下是我的代码: ViewModel:

func getManufacturerList() -> Single<[ManufacturerItem]> {
    return self.fetchManufacturerInteractor.getManufacturerList()
        .map { $0.map { ManufacturerItem(
            manufacturerName: $0.manufacturerName,
            manufacturerID: $0.manufacturerID) } }
}

上面的函数从其他层接收对象数组,然后再次从NetworkLayer获取它。
ViewController:

private func setUpViewBinding() {
    manufacturerViewModel.getManufacturerList()
        .asObservable()
        .bind(to: tableView.rx.items(cellIdentifier: LanguageSelectionTableViewCell.Identifier,
                                     cellType: LanguageSelectionTableViewCell.self)) { row, manufacturer, cell in
            cell.textLabel?.text = manufacturer.manufacturerName
            cell.textLabel?.font = AppFonts.appBoldFont(size: 16).value
            cell.accessibilityIdentifier = "rowLanguage\(row+1)"
            cell.textLabel?.accessibilityIdentifier = tblCellLabelAccessibilityIdentifier
    }.disposed(by: self.disposeBag)
}

现在我应该在哪里添加用于显示/隐藏活动指示器的代码?

1 个答案:

答案 0 :(得分:2)

ViewModel 应该处理显示或隐藏IndicatorView(如果只有一个加载视图),因为您的视图需要笨拙,请使用BehaviorRelay而不是变量(描述变量)

在viewModel中     

// create a subject and set the starter state, every time your viewModel 
// needs to show or hide a loading, just send an event
let showLoading = BehaviorRelay<Bool>(value: true)

// your async function
func getManufacturerList() -> Observable {
  // notify subscriber to show the indicator view
  showLoading.accept(true)

  // do some works


  // notify subscribers to hide the indicator view
  showLoading.accept(false)
}

并在您的视图控制器中

// bind your indicator view to that subject and wait for events
showLoading.asObservable().observeOn(MainScheduler.instance).bind(to: indicatorView.rx.isHidden).disposed(by: disposeBag)
相关问题