9

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

solidcell
  • 7,639
  • 4
  • 40
  • 59
alexxjk
  • 1,681
  • 5
  • 18
  • 30

1 Answers1

17

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
}
solidcell
  • 7,639
  • 4
  • 40
  • 59
  • 2
    Since Variable is planned for deprecation, any thoughts on how to do this with BehaviorRelay - the recommended alternative? behaviorRelay.value.append is not permitted since BehaviorRelay.value is a non-mutating member. – Chuck Krutsinger Oct 05 '18 at 21:29
  • 1
    As mentioned in a comment in the issue, you can get the value of a `BehaviorRelay` by calling `value`. Then you can append to it and feed the new value back in by calling `accept`. https://github.com/ReactiveX/RxSwift/issues/1501#issuecomment-349334148 – solidcell Oct 07 '18 at 18:59
  • 1
    That is what I ended up doing, but since the value is immutable, I am creating a new array rather than appending. There is a performance penalty for doing that. In my testing, the performance hit seems acceptable, so I'll keep it. But I'd love to have a way to do an actual append. – Chuck Krutsinger Oct 08 '18 at 14:52