Skip to content

Instantly share code, notes, and snippets.

@jverkoey
Created February 1, 2017 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jverkoey/77cffb5a77f9f90832dab44c5a8f9ea8 to your computer and use it in GitHub Desktop.
Save jverkoey/77cffb5a77f9f90832dab44c5a8f9ea8 to your computer and use it in GitHub Desktop.
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