Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift double mapping in tableView.rx.itemSelected

I want to get object from tableView.rx.itemSelected and after process it. This method return IndexPath, so I can map this value. But how to get object at index from the ViewModel?

struct ViewModel {
    var items: Observable<[Item]>
}

Approximate I expect something like this (but this flow is wrong):

tableView.rx.itemSelected
        .map { indexPath -> Item in 
        return viewModel.items.map {$0[indexPath.row]}
        }
        ..subscribe(onNext: { [unowned self] item in
        //other actions with Item object
        })
        .disposed(by: disposeBag)

I showed somewhere this possibility, but cant recollect it. Have you some idea how to do it?

like image 510
biloshkurskyi.ss Avatar asked Oct 02 '17 07:10

biloshkurskyi.ss


2 Answers

If you need both indexPath and the model you could combine the 2 methods and transform them in only one observable sequence:

Observable
    .zip(tableView.rx.itemSelected, tableView.rx.modelSelected(String.self))
    .bind { [unowned self] indexPath, model in
        self.tableView.deselectRow(at: indexPath, animated: true)
        print("Selected " + model + " at \(indexPath)")
    }
    .disposed(by: disposeBag)
like image 93
Eduard Avatar answered Sep 22 '22 05:09

Eduard


Also I have found other way add do(onNext:{...}) after itemSelected command:

tableView.rx
    .itemSelected
    .do(onNext: { [unowned self] indexPath in
        self.tableView.deselectRow(at: indexPath, animated: false)
    })
    .map { indexPath -> Item in 
        return viewModel.items.map {$0[indexPath.row]}
    }
    .subscribe(self.viewModel.reviewTimeAction.inputs)
    .disposed(by: disposeBag)
like image 37
biloshkurskyi.ss Avatar answered Sep 22 '22 05:09

biloshkurskyi.ss