Last active
October 4, 2019 08:21
-
-
Save zxzxlch/9f9ff9e200f15d3f0aa7fee376d650b5 to your computer and use it in GitHub Desktop.
Exploring the Signal and SignalProducer objects in ReactiveSwift 1.1
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
import Foundation | |
import ReactiveSwift | |
import Result | |
let a = MutableProperty<String>("") | |
let b = MutableProperty<String>("") | |
let c = MutableProperty<String>("") | |
// Signals are hot | |
let signalDisposable = Signal.combineLatest(a.signal, b.signal, c.signal) | |
.observeValues { aVal, bVal, cVal in | |
print("combined signal = \(aVal + bVal + cVal)") | |
} | |
a.value = "π" | |
b.value = "π" | |
// No output, still awaiting value from C to combine | |
c.value = "π" | |
// Output: combined signal = πππ | |
// Values from all 3 signals have been sent and combined | |
a.value = "π" | |
// Output: combined signal = πππ | |
signalDisposable?.dispose() | |
b.value = "π" | |
// No output because the combined signal has been disposed | |
// SignalProducers are cold | |
var disposable = SignalProducer.combineLatest(a.producer, b.producer, c.producer) | |
.startWithValues { aVal, bVal, cVal in | |
print("combined producer = \(aVal + bVal + cVal)") | |
} | |
// Output: combined producer = πππ | |
// SignalProducers create side-effects. The initial values are sent when the SignalProducer starts. | |
c.value = "πΈ" | |
// Output: combined producer = πππΈ | |
disposable.dispose() | |
// Try a mix of a producer and two signals | |
disposable = a.producer | |
.lift { aSignal in | |
return Signal.combineLatest(aSignal, b.signal, c.signal) | |
} | |
.startWithValues { aVal, bVal, cVal in | |
print("mixed producer = \(aVal + bVal + cVal)") | |
} | |
// Nothing is printed because signals B and C have not sent any values | |
b.value = "π" | |
c.value = "π" | |
// Output: mixed producer = πππ | |
// All values have been sent (A has already sent an initial value because it's a SignalProducer) | |
a.value = "π" | |
// Output: mixed producer = πππ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment