Table and collection view data sources for Combine

CombineDataSources

CombineDataSources provides custom Combine subscribers that act as table and collection view controllers and bind a stream of element collections to table or collection sections with cells.

Usage

The repo contains a demo app in the Example sub-folder that demonstrates visually different ways to use CombineDataSources.

Bind a plain list of elements

var data = PassthroughSubject<[Person], Never>()

data
  .subscribe(subscriber: tableView.rowsSubscriber(cellIdentifier: "Cell", cellType: PersonCell.self, cellConfig: { cell, indexPath, model in
    cell.nameLabel.text = model.name
  }))

Respectively for a collection view:

data
  .subscribe(collectionView.itemsSubscriber(cellIdentifier: "Cell", cellType: PersonCollectionCell.self, cellConfig: { cell, indexPath, model in
    cell.nameLabel.text = model.name
    cell.imageURL = URL(string: "https://api.adorable.io/avatars/100/\(model.name)")!
  }))

Bind a list of Section models

var data = PassthroughSubject<[Section<Person>], Never>()

data
  .subscribe(subscriber: tableView.sectionsSubscriber(cellIdentifier: "Cell", cellType: PersonCell.self, cellConfig: { cell, indexPath, model in
    cell.nameLabel.text = model.name
  }))

Customize the table controller

var data = PassthroughSubject<[[Person]], Never>()

let controller = TableViewItemsController<[[Person]]>(cellIdentifier: "Cell", cellType: PersonCell.self) { cell, indexPath, person in
  cell.nameLabel.text = person.name
}
controller.animated = false

// More custom controller configuration ...

data
  .subscribe(subscriber: tableView.sectionsSubscriber(controller))

Subscribing a completing publisher

Sometimes you'll bind a publisher to your table or collection view and it will complete at a point. When you use subscribe(_) the completion event will release the CombineDataSource subscriber as well and that will likely render the table/collection empty.

In such case you can use the custom operator included in CombineDataSources subscribe(retaining:) that will give you an AnyCancellable to retain the subscriber, like so:

var subscriptions = [AnyCancellable]()
...
Just([Person(name: "test"])
  .subscribe(retaining: tableView.rowsSubscriber(cellIdentifier: "Cell", cellType: UITableViewCell.self, cellConfig: { (cell, ip, person) in
    cell.textLabel!.text = person.name
  }))
  .store(in: &subscriptions)

This will keep the subscriber and the data source alive until you cancel the subscription manually or it is released from memory.

Installation

Swift Package Manager

Add the following dependency to your Package.swift file:

.package(url: "https://github.com/combineopensource/CombineDataSources, from: "0.2")

GitHub