[swift] RxDataSources를 사용한 예제 앱 소개

개요

이번 글에서는 RxDataSources를 사용하여 데이터 바인딩을 간단히 구현하는 예제 앱을 소개합니다. RxDataSources는 RxSwift와 함께 사용되며, UITableView와 UICollectionView 등의 UI 컴포넌트와 데이터를 손쉽게 바인딩할 수 있는 기능을 제공합니다.

준비물

이 예제를 따라하기 위해 다음의 준비물이 필요합니다.

설치

RxDataSources를 설치하기 위해 CocoaPods를 활용합니다. Podfile에 다음과 같은 내용을 추가한 후, pod install을 실행하세요.

target 'YourApp' do
    use_frameworks!
    pod 'RxSwift'
    pod 'RxCocoa'
    pod 'RxDataSources'
end

예제 앱

이번 예제에서는 간단한 할일 목록 앱을 구현하겠습니다. 앱에는 할일 항목의 제목과 완료 여부를 표시하는 기능이 있습니다.

우선, 할일 항목을 담을 구조체를 정의합니다.

struct TodoItem {
    let title: String
    let completed: Bool
}

다음으로, 할일 목록을 표시할 UITableViewController를 생성합니다.

import UIKit
import RxSwift
import RxCocoa
import RxDataSources

class TodoListViewController: UITableViewController {
    
    let disposeBag = DisposeBag()
    let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, TodoItem>>(
        configureCell: { dataSource, tableView, indexPath, item in
            let cell = tableView.dequeueReusableCell(withIdentifier: "TodoCell", for: indexPath)
            cell.textLabel?.text = item.title
            cell.accessoryType = item.completed ? .checkmark : .none
            return cell
        }
    )

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "TodoCell")
        
        let items = [
            TodoItem(title: "Buy groceries", completed: false),
            TodoItem(title: "Do laundry", completed: true),
            TodoItem(title: "Clean the house", completed: false)
        ]
        
        let sections = [SectionModel(model: "", items: items)]
        
        Observable.just(sections)
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
    }
}

위 코드에서 dataSource는 RxDataSources의 RxTableViewSectionedReloadDataSource를 사용하여 셀을 구성하는 방법을 설정합니다. configureCell 클로저를 통해 셀을 구성하고 반환합니다.

앱을 실행하면 할일 목록이 테이블뷰에 표시되고, 셀을 탭하여 완료 상태를 변경할 수 있습니다.

결론

RxDataSources를 사용하면 UITableView 또는 UICollectionView와 함께 데이터 바인딩을 쉽게 구현할 수 있습니다. 이를 통해 코드의 가독성과 유지보수성이 향상되며, 리액티브 프로그래밍의 장점을 더욱 효과적으로 활용할 수 있습니다.

참고 자료