Julian Toya Angeles
Julian Toya Angeles

Reputation: 77

RxSwift Conditional Observable

I'm new to RxSwift and had a question about the Observables. In particular, I'm trying to have an Observable (based on viewDidAppear) emit only when a subview is visible (some boolean flag is true).

So far, both the skip- and take- operators (and their like) looked like the most promising. The only problem is, this subview can appear/disappear every time a user visits the parent view (depending on some conditions).

Based on my limited understanding, the above operators take into effect when the condition is meant once (and will complete). Is there something I'm misunderstanding or maybe there is a way to achieve my goal?

Any and all help is much appreciated!

Upvotes: 2

Views: 362

Answers (1)

Daniel T.
Daniel T.

Reputation: 33967

The essence of functional reactive programming is to specify the dynamic behavior of a value completely at the time of declaration. -- Heinrich Apfelmus

So the question is, what is the dynamic behavior of the value you are defining?

In order to make a sub-view of your VC's view appear and disappear, its isHidden property needs to be updated at the right times. So what are the triggers that cause this sub-view to appear and disappear? Turn those into Observables, combine them with some logic and bind that Observable<Bool> to the subview's rx.isHidden property.

Unfortunately, you haven't given enough information for me to help with that, but if you update your question, I will update my answer.

In the mean time, I'll leave you with this example from one of my production apps. The invariant is that the benefitKeysView should only be visible if there is more than one benefitColor.

func setupBenefitKeys(benefitKeysView: UIView, disposeBag: DisposeBag, benefitColors: Observable<BenefitColorsData>) {
    benefitColors
        .map { $0.benefitColors.count < 2 }
        .startWith(true)
        .bind(to: benefitKeysView.rx.isHidden)
        .disposed(by: disposeBag)
}

struct BenefitColorsData {
    let benefitColors: [UIColor]
}

Upvotes: 0

Related Questions