RxSwift 3.1 UITableView data source not working

2.6k views Asked by At

I am using RxSwift 3.1 (Galois) via Carthage in my new project and I've just tried to bind the data to UITableView using some examples I found online and in the documentation - one of them being this file: https://github.com/ReactiveX/RxSwift/blob/master/RxExample/RxExample/Examples/SimpleTableViewExample/SimpleTableViewExampleViewController.swift

My code looks like this right now (I've tried to dumb it down already because what I wanted to work didn't):

class ChooseCityView: UIViewController, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {

        super.viewDidLoad()

        let dataSource = Observable.just((0..<20).map { "\($0)" })
        let disposeBag = DisposeBag()

            dataSource.bindTo(tableView.rx.items(cellIdentifier: "CityCell", cellType: UITableViewCell.self)) {
                (row, city, cell) in
                cell.backgroundColor = .white
                cell.textLabel?.text = "test \(city)"
            }.addDisposableTo(disposeBag)

        // Remove empty cells
        tableView.tableFooterView = UIView()

    }
}

Still, after running the app in simulator this will not show any rows. I have a prototype cell on tableView called "CityCell", with type Basic. Also, I made sure the outlet is bound with the actual tableView. What could I be doing wrong? Or is this a bug?

Thanks in advance :)

1

There are 1 answers

1
Artem Novichkov On BEST ANSWER

After some time, I found solution. Add disposeBag as view controller's property. For your code:

class ChooseCityView: UIViewController, UITableViewDelegate  {

    @IBOutlet weak var tableView: UITableView!
    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        let dataSource = Observable.just((0..<20).map { "\($0)" })

        dataSource.bindTo(tableView.rx.items(cellIdentifier: "CityCell", cellType: UITableViewCell.self)) {
            (row, city, cell) in
            cell.backgroundColor = .white
            cell.textLabel?.text = "test \(city)"
            }.addDisposableTo(disposeBag)

        // Remove empty cells
        tableView.tableFooterView = UIView()
    }
}