6

How do I populate the NSTableview with an array using reactive framework? In iOS for UITableview:

self.viewModel.arrayElements.asObservable()
        .observeOn(MainScheduler.instance)
        .bind(to: detailsTableView.rx.items(cellIdentifier: "comment", cellType: UITableViewCell.self)){
            (row,element,cell) in
                 cell.addSubview(cellView)
        }.addDisposableTo(disposeBag)

how can i achieve the same for NSTableView

enter image description here

Padma
  • 83
  • 7

2 Answers2

0

I ran into a similar need, and solved it with a BehaviorRelay (using RxSwift 5).

The BehaviorRelay acts as a mediator so it's possible to use regular NSTableViewDataSource and NSTableViewDelegate protocols

The important part is the self.detailsTableView.reloadData() statement which tells the tableview to reload the data, it is not triggered automatically.

Something like this:

var disposeBag = DisposeBag()
var tableDataRelay = BehaviorRelay(value: [Element]())

func viewDidLoad() {
    viewModel.arrayElements.asObservable()
        .observeOn(MainScheduler.instance)
        .bind(to: tableDataRelay).disposed(by: disposeBag)

    tableDataRelay
        .observeOn(MainScheduler.instance)
        .subscribe({ [weak self] evt in
            self.detailsTableView.reloadData()
        }).disposed(by: disposeBag)
}

func numberOfRows(in tableView: NSTableView) -> Int {
    return tableDataRelay.value.count
}

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
    let element = tableDataRelay.value[row]
    let cellView = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: nil) as? NSTableCellView

    cellView?.textField?.stringValue = element.comment
    return cellView
}


Jimmy Stenke
  • 11,140
  • 2
  • 25
  • 20
-1

Try the below, you should use drivers not observables

read this https://github.com/ReactiveX/RxSwift/blob/master/Documentation/Traits.md

import RxSwift
import RxCocoa

let data = Variable<[String]>([])
let bag  = DisposeBag()

override func viewDidLoad() {
super.viewDidLoad()

    data.asDriver.drive( tableView.rx.items(cellIdentifier: "idenifier")){(row:Int, comment:String, cell:UITableViewCell) in
        cell.title = report
    }.disposed(by:bag)
}
Mark Gilchrist
  • 1,972
  • 3
  • 24
  • 44