简体   繁体   中英

RxSwift: Append elements to Observable<[_]>

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM