Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift: Append elements to Observable<[_]>

Tags:

swift

rx-swift

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<[_]>.

like image 914
alexxjk Avatar asked May 08 '16 17:05

alexxjk


1 Answers

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
}
like image 191
solidcell Avatar answered Sep 21 '22 19:09

solidcell