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.
Table of Contents
1.1 Bind a plain list of elements
1.2 Bind a list of Section models
1.2 Customize the table controller
1.3 Subscribing a completing publisher
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
.receive(subscriber: tableView.rowsSubscriber(cellIdentifier: "Cell", cellType: PersonCell.self, cellConfig: { cell, indexPath, model in
cell.nameLabel.text = model.name
}))
Bind a list of Section models
var data = PassthroughSubject<[Section<Person>], Never>()
data
.receive(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")
License
CombineOpenSource is available under the MIT license. See the LICENSE file for more info.
Credits
Created by Marin Todorov for CombineOpenSource.
Inspired by RxDataSources and RxRealmDataSources.