RxDataSources for MultipleSections with Animation and without Animations CollectionView and TableView Reusable Code

Varender Singh
3 min readSep 23, 2020

--

Everyone is aware of RxSwift and its mighty capabilities which we can use to make our code more reactive on the data changes. So I will skip this part of the introduction to Rx and show you how I implemented the RxDataSource with reusability.

Implementation

  1. Add RxSwift, RxDataSources, RxCocoa to project using Cocoapods
  2. Declare an Enum for the Sections you want to place in the UICollectionView or UITableView.

2. Import File From this link in your project https://github.com/varen1994/RxSwiftAnimatableSections/blob/master/MultipleSectionDemoWithRx/Helper/RxWrapperSectionAndItemModels.swift

3. You have to use the struct ZISectionWrapperModel and class ZIWrapperItem defined in RxWrapperSectionAndItemModels.swift for creating sections and items for both UICollectionView and UITableView.

4. Define a Behaviour Relay object in the ViewModel or ViewController for throwing all changes in the model.

5. In ViewDidLoad bind this subject with the RxDataSources objects. For this demo code, the item will always of Type ZIWrapperItem.

6. Now you can add new sections to this Behaviour Relay object like this code.

Always you have to convert all the sections items to ZIWrapperItem array using method convertItemOfAnyToZIWrapperItem defined in ZISectionWrapperModel.

and that’s it. This will help you to implement the following objects with ease

  • RxTableViewSectionedAnimatedDataSource
  • RxTableViewSectionedReloadDataSource
  • RxCollectionViewSectionedReloadDataSource
  • RxCollectionViewSectionedAnimatedDataSource

Here is the Code Repository link https://github.com/varen1994/RxSwiftAnimatableSections

Whats inside the RxWrapperSectionAndItemModels.swift File?

  1. ZISectionWrapperModel:- Confirms to protocol AnimatableSectionModelType of RxDataSources which states that Each Section and Item should have a different Identity. So For Section different identity, I am using Enums defined in the second step of implementation.

public protocol AnimatableSectionModelType: SectionModelType

, IdentifiableType where Item: IdentifiableType, Item: Equatable { }

and each ZISectionWrapperModel contains Items which will be of type ZIWrapperItem.

2. ZIWrapperItem:- Confirms to the protocol IdentifiableType,Equatable. For each ZIWrapperItem, you should have a different identity of any type but I am using String type and I am assigning each Item a different identity using the convertItemOfAnyToZIWrapperItem method of ZISectionWrapperModel. Where I am concatenating sectionName + “\(indexOfArrayItem)” for creating different identities of items.

Thanks for reading the blog. In case anyone wants a more detailed explanation of implementation feel free to mail me at varendersingh130@gmail.com

--

--