Question

I'm would like to know your opinion of what is an ideomatic way writing a OR function in functional reactive programming.

That is, if I have x number of signals which can return a truthy or falsy value, how can I evaluate if at least one signal is truthy, or all signals are falsy? Finally I would like to send the result (true/false) as a result.

I can think of a number of ways of accomplishing this but they all feel bloated and over engineered.

Was it helpful?

Solution

It sounds like a basic combineLatest operation to me. In RxSwift that would be something like:

func anyTrue(streams: [Observable<Bool>]) -> Observable<Bool> {
    return streams.combineLatest { $0.contains(true) }
}

The above will begin emitting values after all the inputs have emitted at least one value. As long as at least one of the streams have emitted true, it will emit true, otherwise it will emit false.

In ReactiveCocoa, this would be:

func anyTrue(streams: [Signal<Bool, NoError>]) -> Signal<Bool, NoError> {
    return combineLatest(streams).map { $0.contains(true) }
}
Licensed under: CC-BY-SA with attribution
scroll top