【问题标题】:Display activity indicator with RxSwift and MVVM使用 RxSwift 和 MVVM 显示活动指示器
【发布时间】:2019-01-16 08:44:28
【问题描述】:

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

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

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

【问题讨论】:

    标签: ios swift rx-swift


    【解决方案1】:

    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)
    

    【讨论】:

    • 有没有办法以一种更被动的方式做到这一点,而无需显示加载主题?是否有可以使用的运算符告诉您何时开始加载操作?
    猜你喜欢
    • 2017-04-26
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2016-08-01
    • 2019-02-04
    • 2016-12-12
    相关资源
    最近更新 更多