首页 > 解决方案 > 使用 RxSwift 和 MVVM 显示活动指示器

问题描述

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

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

上面的函数接收来自其他层的对象数组,该层再次从 NetworkLayer 获取它。
视图控制器:

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)
}

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

标签: iosswiftrx-swift

解决方案


ViewModel应该处理显示或隐藏 IndicatorView(如果有单个加载视图),因为您的视图需要是哑的,使用 BehaviorRelay 而不是变量(变量已被弃用)

在视图模型中

// 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)

推荐阅读