Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift in swift 4, binding data to a tableview

I have a problem trying to follow this introduction to the MVVM pattern and RxSwift.

About half way down, he binds the data source (cars) to the tableView. This is the part I can't seem to get working in swift 4.

I'm using the following pods:

pod 'RxSwift', '4.0.0-beta.0'
pod 'RxCocoa', '4.0.0-beta.0'

This is the code I've tried with the error im getting (thought is was easier to see on a picture): enter image description here

I have looked at all other questions mentioning a fix for this:
RxSwift, RxCocoa and UITableview
Cannot set bind(to: UITableView) with RxSwift Variable asObservable()

But can't seem to make it work with the swift 4 version. Hope you guys can help me out :)

like image 631
Alpo Avatar asked Oct 03 '17 13:10

Alpo


1 Answers

The error message is misleading. The problem lies in the way you initialize your cars property. Your cars Variable wraps an Optional type. You cannot bind that to a table view.

Change the initialization to the following line and everything is fine:

var cars = Variable((UIApplication.shared.delegate as! AppDelegate).cars)

By the way, you do not have to wrap the cars array in a Variable, you can leave it as an Array:

let cars = (UIApplication.shared.delegate as! AppDelegate).cars

And then use Observable.of() to bind it to the table view:

Observable.of(cars).bind(to: tableView.rx.items(cellIdentifier: "CarCell", cellType: CarTableViewCell.self)) { (_, carViewModel: CarViewModel, cell) in
   cell.carViewModel = carViewModel
}.addDisposableTo(disposeBag)
like image 68
joern Avatar answered Nov 05 '22 07:11

joern