Skip to content

Instantly share code, notes, and snippets.

@zxzxlch
Last active October 4, 2019 08:21
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 zxzxlch/9f9ff9e200f15d3f0aa7fee376d650b5 to your computer and use it in GitHub Desktop.
Save zxzxlch/9f9ff9e200f15d3f0aa7fee376d650b5 to your computer and use it in GitHub Desktop.
Exploring the Signal and SignalProducer objects in ReactiveSwift 1.1
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