简体   繁体   中英

Observe object change in other ViewController in RxSwift

I have a ViewController with a UICollectionView and its elements are bound and cells created via:

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

I also react to the user taps via:

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)

The property in the xViewController for item is of Type ProfileItem? . How can changes to item in the XViewController be bound to the collectionView cell?

Thanks in advance

Your XViewController needs an Observable that emits a new item at the appropriate times... Then realize that this observable can affect what profileItems , or at least your view model, emits.

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)

Now you need to feed xResult into your view model.

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