Reload Tableview using RxSwift
Asked Answered
S

3

8

I am using RxSwift for tableview. I need to reload my table each time after getting data from api but I'm failed to do this. 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.

enter image description here

Sea answered 20/3, 2017 at 8:54 Comment(1)
what did you actually try?Moiety
S
13

I have found the issue. My array was not being getting updated correctly. I did the following changes.

Declare dataSource variable of ModelClass:

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:

dataSource.value = self.array

Now each time when value of dataSource will be changed, table view will be reloaded.

Sea answered 20/3, 2017 at 11:52 Comment(0)
P
9

Avoid using "Variable" because of this concept will be deprecated from RxSwift but official migration path hasn't been decided yet.

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

Hence, recommend using RxCocoa.BehaviorRelay instead.

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

Bind to 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 :)

Preterite answered 1/9, 2018 at 4:48 Comment(2)
How can man force reload the tableView after updating all it's rows using Driver?Clevelandclevenger
Hi @Blackbeard, I am not sure what you mean, the above code the data source had been bind to the UI, so once you update the data source the UI will update automatically. If you want to refresh or fetch more data you can simply use "dataSource.accept(updatedModels)" or "dataSource.accept(models + newModels)". If I am not answering what you ask, please describe it more and let's help and learn more :)Preterite
C
3

Let

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

Whenever you hit your API, put your fetched results in self.array.value and it will automatically gets updated.

 self.array.asObservable().bindTo(ResultsTable.rx.items(cellIdentifier: "SearchCell", cellType:SearchCell.self)) 
   { (row, element, cell) in
        cell.configureCell(element: element)
   }.addDisposableTo(disposeBag)
Counterwork answered 2/8, 2017 at 3:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.