简体   繁体   English

使用RxSwift重新加载Tableview

[英]Reload Tableview using RxSwift

I am using RxSwift for tableview. 我正在使用RxSwift进行tableview。 I need to reload my table each time after getting data from api but I'm failed to do this. 每次从api获取数据后我都需要重新加载我的表但是我没有这样做。 I couldn't find any solution for that. 我找不到任何解决方案。 Can anybody help? 有人可以帮忙吗?

I have an array of places obtain from response of an Api.I have used this code in view did load, but its is not being called when array is updated. 我有一个从Api的响应获得的地方数组。我在视图中使用了这个代码加载,但是在更新数组时它没有被调用。

在此输入图像描述

I have found the issue. 我发现了这个问题。 My array was not being getting updated correctly. 我的阵列没有正确更新。 I did the following changes. 我做了以下更改。

Declare dataSource variable of ModelClass: 声明ModelClass的dataSource变量:

let dataSource = Variable<[SearchResult]>([])

Bind it with the table view right now it is empty: 现在将它与表视图绑定为空:

dataSource.asObservable().bindTo(ResultsTable.rx.items(cellIdentifier: "SearchCell")){ row,Searchplace,cell in
    if let C_cell = cell as? SearchTableViewCell{
        C_cell.LocationLabel.text = Searchplace.place
    }
}.addDisposableTo(disposeBag)

Then store my updated array in it that contains the searchPlaces: 然后将包含searchPlaces的更新数组存储在其中:

dataSource.value = self.array

Now each time when value of dataSource will be changed, table view will be reloaded. 现在,每次更改dataSource的值时,将重新加载表视图。

Avoid using "Variable" because of this concept will be deprecated from RxSwift but official migration path hasn't been decided yet. 避免使用“变量”,因为此概念将从RxSwift弃用,但官方迁移路径尚未确定。

REF: https://github.com/ReactiveX/RxSwift/issues/1501 REF: https//github.com/ReactiveX/RxSwift/issues/1501

Hence, recommend using RxCocoa.BehaviorRelay instead. 因此,建议使用RxCocoa.BehaviorRelay。

let dataSource = BehaviorRelay(value: [SearchResultModel]())

Bind to tableView 绑定到tableView

 self.dataSource.bind(to: self.tableView.rx.items(cellIdentifier: "SearchCell", cellType: SearchCell.self)) { index, model, cell in
      cell.setupCell(model: model)
 }.disposed(by: self.disposeBag)

after fetch data: 获取数据后:

let newSearchResultModels: [SearchResultModel] = ..... //your new data
dataSource.accept(newSearchResultModels)

Hope this can help :) 希望这可以帮助:)

Let

array = Variable<[SearchResult]>([])

Whenever you hit your API, put your fetched results in self.array.value and it will automatically gets updated. 每当您点击API时,将获取的结果放在self.array.value ,它将自动更新。

 self.array.asObservable().bindTo(ResultsTable.rx.items(cellIdentifier: "SearchCell", cellType:SearchCell.self)) 
   { (row, element, cell) in
        cell.configureCell(element: element)
   }.addDisposableTo(disposeBag)

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

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