0

I have an iOS app that I am rewriting to use RxSwift and RxCocoa. It works really well, but I have problems with collection view data bindings.

In my app, I perform data bindings when viewWillAppear is called on a view controller, for instance:

let view = collectionView
getStuff().bind(to: view.rx.items(cellIdentifier: "Cell", cellType: Cell.self)) {
    row, item, cell in
    cell.setup(with: item)
}.disposed(by: disposeBag)

```

This works great - my data is correctly bound to my collection views.

However, to avoid having active bindings for view controllers that are not currently visible, I dealloc disposeBag whenever viewWillDisappear is called. I then recreate the dispose bag and rebind data whenever the vc is displayed again.

My problem is, that when I rebind data to the collection view, the content offset is reset. Consider a scenario where I list content and navigate to a new view controller when an item is tapped. Whenever I go back to the list, the new data bind will cause the scroll view to scroll to top.

The default behavior for a collection view is to keep its offset even if the data source changes and reloadData is called. Am I missing something here or am I doing something wrong?

Daniel Saidi
  • 6,079
  • 4
  • 27
  • 29

1 Answers1

0

It sounds like the data you're binding your collectionview to is released completely after clearing your disposeBag. Then, when viewWillAppear is called again, your Observable might briefly be without data, thus resetting the offset to 0.0.

In case you are not familiar with these terms, look into hot and cold Observables. If you are getting your content via a remote API call, it may be wise to maintain a reference to your fetched data even after the view controller navigates away. That way you can be sure the data is not fetched again when returning to the original VC.

RamwiseMatt
  • 2,717
  • 3
  • 16
  • 22