ios - 使用 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)
}
现在我应该在哪里添加显示/隐藏活动指示器的代码?
解决方案
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)
推荐阅读
- batch-file - 使用 MS 批处理将程序的(无休止)输出分配给变量
- git - 验证 Git 提交是否只移动行
- rust - 是否可以创建一个自定义派生来防止编译时类型之间的循环?
- c# - Unity:第二次触摸根本不起作用。如何修复此错误?
- javascript - 如何使用 javascript 将 Blur 事件触发到窗口
- mongodb - 无法使用命令“go get go.mongodb.org/mongo-driver/mongo”获取 mongo-go 驱动程序
- java - 我无法让任何 indexOf() 函数为我编写的这段代码工作
- python - 正则表达式查找除特殊字符之间的所有单词之外的所有单词
- spring-boot - 在春季启动中使用@Onetomany @JoinColumn 进行一对多关联?
- android - BuildConfig定义多次,Gradle Test Build报错