Created
February 1, 2017 04:04
-
-
Save jverkoey/77cffb5a77f9f90832dab44c5a8f9ea8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public func openValve<O: MotionObservableConvertible>(whenAllTrue observables: [O]) -> MotionObservable<T> where O.T == Bool { | |
return MotionObservable<T> { observer in | |
var upstreamSubscription: Subscription? | |
var connectUpstream = { | |
upstreamSubscription = self.asStream().subscribe(next: observer.next, | |
state: observer.state, | |
coreAnimation: observer.coreAnimation) | |
} | |
var states: [Bool] = observables.map { _ in false } | |
var valveSubscriptions: [Subscription] = [] | |
for (index, observable) in observables.enumerated() { | |
let subscription = observable.asStream().subscribe(next: { value in | |
states[index] = value | |
var anyFalse = false | |
for state in states { | |
if state == false { | |
anyFalse = true | |
break | |
} | |
} | |
let shouldOpen = !anyFalse | |
if shouldOpen && upstreamSubscription == nil { | |
connectUpstream() | |
} | |
if !shouldOpen && upstreamSubscription != nil { | |
upstreamSubscription?.unsubscribe() | |
upstreamSubscription = nil | |
} | |
}, state: { _ in }, coreAnimation: { _ in }) | |
valveSubscriptions.append(subscription) | |
} | |
return { | |
for subscription in valveSubscriptions { | |
subscription.unsubscribe() | |
} | |
upstreamSubscription?.unsubscribe() | |
valveSubscriptions = [] | |
upstreamSubscription = nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment