From 46a7262ee059b96bebf11ac1f5387f3f44954be3 Mon Sep 17 00:00:00 2001 From: Tyler Cloutier Date: Sat, 12 Nov 2016 01:11:38 -0800 Subject: [PATCH] Improved partition to all execute the predicate a single time. --- Sources/Signal.swift | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/Sources/Signal.swift b/Sources/Signal.swift index c79fd09..906ddd1 100644 --- a/Sources/Signal.swift +++ b/Sources/Signal.swift @@ -287,28 +287,19 @@ public extension SignalType { /// Splits the signal into two signals. The first signal in the tuple matches the /// predicate, the second signal does not match the predicate public func partition(_ predicate: @escaping (Value) -> Bool) -> (Signal, Signal) { - let left = Signal { observer in - return self.on { (event: Event) -> Void in - guard let value = event.value else { - observer.sendEvent(event) - return - } - - if predicate(value) { - observer.sendNext(value) - } + let (left, leftObserver) = Signal.pipe() + let (right, rightObserver) = Signal.pipe() + self.on { (event: Event) -> Void in + guard let value = event.value else { + leftObserver.sendEvent(event) + rightObserver.sendEvent(event) + return } - } - let right = Signal { observer in - return self.on { (event: Event) -> Void in - guard let value = event.value else { - observer.sendEvent(event) - return - } - - if !predicate(value) { - observer.sendNext(value) - } + + if predicate(value) { + leftObserver.sendNext(value) + } else { + rightObserver.sendNext(value) } } return (left, right)