[TIL] RxDataSources

Eden·2025년 7월 31일

RxDataSources는 RxSwift와 함께 사용되는 라이브러리로, UITableViewUICollectionView의 데이터 바인딩을 더 쉽게 도와줍니다. Diffing, Section 관리 등을 효율적으로 처리할 수 있어 반응형 UI 구성에 유용합니다.


주요 특징

  • 섹션 기반의 데이터 처리 가능
  • Diffing 기능을 통한 성능 향상
  • 편리한 바인딩 방식 제공 (bind, drive 등)
  • 셀 구성 및 데이터 업데이트가 간결

필수 구성 요소

1. SectionModel 정의

import RxDataSources

struct MySection {
    var header: String
    var items: [Item]
}

extension MySection: SectionModelType {
    typealias Item = String

    init(original: MySection, items: [Item]) {
        self = original
        self.items = items
    }
}

2. DataSource 생성

let dataSource = RxTableViewSectionedReloadDataSource<MySection>(
    configureCell: { _, tableView, indexPath, item in
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = item
        return cell
    },
    titleForHeaderInSection: { ds, index in
        return ds.sectionModels[index].header
    }
)

3. ViewModel에서 Observable 데이터 준비

let sections = Observable.just([
    MySection(header: "First", items: ["Apple", "Banana"]),
    MySection(header: "Second", items: ["Carrot", "Daikon"])
])

4. ViewController에서 바인딩

sections
    .bind(to: tableView.rx.items(dataSource: dataSource))
    .disposed(by: disposeBag)

RxCollectionView에서도 동일하게 사용

  • RxCollectionViewSectionedReloadDataSource를 사용하면 UICollectionView에 적용 가능
  • 셀 사이즈, 레이아웃은 UICollectionViewFlowLayout 혹은 UICollectionViewCompositionalLayout과 병행

주의사항

  • SectionModelType 프로토콜을 반드시 준수해야 함
  • 셀 재사용 식별자 누락 시 런타임 오류 발생 가능
  • disposeBag 누락 시 메모리 누수 가능

요약

RxDataSources는 RxSwift 기반 프로젝트에서 리스트 UI 구성의 복잡도를 줄이고, 선언적 바인딩을 통해 코드 가독성과 유지보수성을 향상시켜줍니다.

profile
iOS Dev

0개의 댓글