在RxSwift中观察其他ViewController中的对象更改

时间:2020-09-16 22:25:21

标签: ios swift rx-swift

我有一个带有UICollectionView的ViewController,其元素已绑定,并通过以下方式创建了单元格:

 self.viewModel.profileItems.bind(to: self.collectionView.rx.items){ (cv, row, item) ...

我还通过以下方式对用户的点击做出反应:

self.collectionView.rx.modelSelected(ProfileItem.self).subscribe(onNext: { (item) in
        if(/*special item*/) {
            let xVC = self.storyboard?.instantiateViewController(identifier: "x") as! XViewController
            xVC.item = item
            self.navigationController?.pushViewController(xVC, animated: true)
        } else {
            // other generic view controller
        }
    }).disposed(by: bag)

xViewController中item的属性为ProfileItem?类型。如何将XViewController中对item的更改绑定到collectionView单元?

预先感谢

1 个答案:

答案 0 :(得分:0)

您的XViewController需要一个可观察的对象,该对象在适当的时间发出新的项目...然后意识到,这个可观察的对象可以影响profileItems或至少您的视图模型所发出的对象。

let xResult = self.collectionView.rx.modelSelected(ProfileItem.self)
    .filter { /*special item*/ }
    .flatMapFirst { [unowned self] (specialItem) -> Observable<Item> in 
        let xVC = self.storyboard?.instantiateViewController(identifier: "x") as! XViewController
        xVC.item = item
        self.navigationController?.pushViewController(xVC, animated: true)
        return xVC.observableX // this needs to complete at the appropriate time.
    }

self.collectionView.rx.modelSelected(ProfileItem.self)
    .filter { /*not special item*/ }
    .bind(onNext: { [unowned self] item in 
        // other generic view controller
    }
    .disposed(by: bag)

现在,您需要将xResult填充到视图模型中。