RxSwift: Append elements to Observable<[_]>

alexxjk picture alexxjk · May 8, 2016 · Viewed 9.9k times · Source

I have an array (Observable<[_]>) that is a datasource for a tableview. I want to be able to append new elements to it and update the tableview every time new elements are appended to the array. I can't find how to add new elements to Observable<[_]>.

Answer

solidcell picture solidcell · May 9, 2016

Use a Subject such as Variable. Then just treat the value property as your Array and append to it to add new elements. Subscribe to the Variable via asObservable().

I've simplified the code example by using String, however you'll want to use some kind of UITableViewCell.

let dataSource = Variable<[String]>([])

dataSource.value.append("some string A")

dataSource.asObservable()
    .subscribeNext { e in
        print(e)
    }
    .addDisposableTo(disposeBag)

dataSource.value.append("some string B")

Once you have your dataSource, you'll want to hook it up to a tableView via

dataSource.asObservable().bindTo(yourTableView.rx_itemsWithCellIdentifier("MyCellClass", cellType: MyCellClass.self)) { (row, element, cell) in
      // do your cell configuration here
}