简体   繁体   English

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

[英]Display activity indicator with RxSwift and MVVM

I have a layered architectured application where I am getting array of objects in ViewModel and binding it with tableview in ViewController. 我有一个分层的体系结构的应用程序,我在其中获取ViewModel中的对象数组,并将其与ViewController中的tableview绑定。 Following is my code: ViewModel: 以下是我的代码:ViewModel:

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

Above function receives array of objects from some other layer which again gets it from NetworkLayer. 上面的函数从其他层接收对象数组,然后再从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)
}

Now where should I add the code for showing/hiding the activity indicator? 现在,我应该在哪里添加用于显示/隐藏活动指示器的代码?

ViewModel should handles showing or hiding IndicatorView (if there is a single loading view) because your view needs to be dumb, use BehaviorRelay instead of variable (variable is depricated) 由于您的视图需要笨拙,因此ViewModel应该处理显示或隐藏IndicatorView(如果有一个加载视图),请使用BehaviorRelay而不是变量(描述变量)

in viewModel 在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)
}

and in your view controller 并在您的视图控制器中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM