- Building from Xcode project no longer warns about use of deprecated
class
keyword usage. (#3726, kudos to @michalsrutek) - Updated Carthage xcconfig dependency to 1.1 for proper building arm64 macOS variants.
- Fixed missing Foundation import when building with SPM in Xcode 12.5. (#3725, kudos to @TimPapler)
- Requires ReactiveSwift 6.6.0 or later.
- The minimum deployment target for iOS has been raised consistently to 9.0 across all integration mediums.
11.0.01. Binding for WKInterfaceActivityRing
has been removed, since it causes watchOS builds to be linked with HealthKit, leading to potential App Store rejections for apps who do not use HealthKit. (#3706)
Users who depend on the WKInterfaceActivityRing
binding should consider replicating them in their projects instead.
- Don't include code which uses unavailable classes (like
NSSlider
) when targeting macOS Catalyst (#3698, kudos to @nkristek) - Fixed watchOS build issues. (#3703, kudos to @JaviSoto)
- Update ReactiveSwift to 6.2.
- Updated
README.md
to reflect Swift 5.1 compatibility and point snippets to 10.1.0 (#3691, kudos to @Marcocanc) - Support for Swift Package Manager (#3692, #3676 & #3693, kudos to @fabio-cerdeiral-ck, @sharplet and @simba909)
- Update dependencies so ReactiveCocoa can be used with Xcode 11 (#3677, kudos to @olejnjak)
- Add a binding target for the
barTintColor
ofUINavigationBar
(#3675, kudos to @rehatkathuria) - Add reactive extensions for standard WatchKit interface objects. (#3670, kudos to @tdimeco)
- Fix crashes of
NSObject.signal(for:)
andNSObject.producer(for:)
with Objective-C enums (#3667, kudos to @gfontenot)
- Update ReactiveSwift to 6.0
- Remove dependency on antitypical/Result
Upgrade to master
- If you have used
Result
only as dependency ofReactiveSwift
, remove all instances ofimport Result
,import enum Result.NoError
orimport struct Result.AnyError
and remove theResult
Framework from your project. - Replace all cases where
NoError
was used in aSignal
orSignalProducer
withNever
- Replace all cases where
AnyError
was used in aSignal
orSignalProducer
withSwift.Error
- Make UITextField and UITextView text and attributedText values non-optional. (#3591, kudos to @Marcocanc)
- KVO observations can now be made with Smart Key Path in Swift 3.2+, using
producer(for:)
andsignal(for:)
available onNSObject.reactive
. (#3491, kudos to @andersio) - Fix warnings for deprecated use of Swift's allocate/deallocate methods.
- Update Quick (2.0.0) and Nimble (8.0.1).
- Update ReactiveSwift to 5.0.
- Added
applicationIconBadgeNumber
binding target toUIApplication
(#3589, kudos to @cocoahero). - Add extension for
alphaValue
property ofNSView
class. (#3636, kuds to @eimantas) - Add extension for
isHidden
property ofNSView
class. (#3634, kudos to @eimantas)
- ReactiveMapKit has now platform specific build targets and schemes. (#3625, kudos to @andersio)
- Add extensions for several properties on
WKInterfaceLabel
andWKInterfaceButton
. (#3616, kudos to @yoching) - Add
swift_version
to podspecs (#3622, kudos to @olejnjak) - Introduce Lifetime.of(_:) which retrieves the lifetime of any Objective-C or Swift native object. (#3614, kudos to @ra1028)
- Fixed an issue of
SignalProducer.take(duringLifetimeOf:)
incorrectly retaining its argument. (#3615, kudos to @andrei-kuzma)
- Add extensions for several properties on
UIBarButtonItem
(#3586, kudos to @asmallteapot).
-
Add support for Cocoapods 1.5.0 static frameworks (#3590, kudos to @mishagray)
-
Add
becomeFirstResponder
andresignFirstResponder
extensions toUIResponder
. (#3585, kudos to @Marcocanc) -
Added
title
binding target toUIViewController
(#3588, kudos to @cocoahero). -
Added several trigger signals for view lifecycle events to
UIViewController
(#3588, kudos to @cocoahero).
-
Fixed a compilation issue related to SR-7299. (#3580)
-
Improved the interoperability of method interception. (#3570, kudos to @andersio)
-
Add
showsCancelButton
,textDidBeginEditing
andtextDidEndEditing
extensions toUISearchBar
. (#3565, kudos to @banjun) -
NotificationCenter.reactive.keyboard(_:)
for system keyboard notification by the event types. (#3566, kudos to @ra1028) -
Add extensions for several properties on
UINavigationItem
. (#3576, kudos to @asmallteapot) -
Add extension for
search
on MKLocalSearchRequest. (#3571, kudos to @Marcocanc)
- Fix an issue preventing ReactiveCocoa from being built with the Swift 3.2 language mode. (#3556)
-
Requires ReactiveSwift 3.1.0 Release Candidate 1. (#3555)
-
Added reactive extension for AppKit's NSTextView. (#3549, kudos to @Palleas)
-
Added
tintColor
binding target toUIView
. (#3542, kudos to @iv-mexx) -
Fixed
DynamicProperty
for optional properties. (#3548, kudos to @iv-mexx) -
Made
makeBindingTarget
available on Reactive extensions on all objects, not justNSObject
. (#3545, kudos to @Burgestrand)
-
Update ReactiveSwift to 3.0.
-
Added
placeholder
binding target toUITextField
. (#3536)
-
UISearchBar has gained more reactive bindings and signals. (#3531, kudos to @andersio)
Signals: Search Button Clicked, Bookmark Button Clicked, Results List Clicked, Selected Scope Button Index
Binding Target: Selected Scope Button Indices.
-
Requires ReactiveSwift 3.0.0 alpha 1.
-
ReactiveCocoa is now compatible with the Swift 4.0 language mode, in addition to the Swift 3.2 compatibility mode. (#3526, kudos to @andersio)
-
MapKit reactive bindings have been moved to a new ReactiveMapKit framework. (#3524)
Sources that use the MapKit bindings are now required to import ReactiveMapKit.
For all Xcode project users (including Carthage), targets need to be configured to link against ReactiveMapKit. For CocoaPods users, the framework is offered as a standalone podspec, so the Podfile needs to be updated with a new entry.
-
Added
cancelButtonClicked
signal toUISearchBar
. -
Subscripting
reactive
with a key path now yields a correspondingBindingTarget
under Swift 3.2+. (#3489, kudos to @andersio)Example:
label.reactive[\.text] <~ viewModel.title
- Disabled code coverage data to allow app submissions with Xcode 9.0 (see Carthage/Carthage#2056, kudos to @NachoSoto)
- [Xcode 9 beta 5] Fixed an issue causing infinite recursion in the Swift runtime. (#3498, kudos to @andersio)
-
NSObject
reactive extensions now work in generic environments that are limited toNSObjectProtocol
. (#3484, kudos to @nickdomenicali) -
New reactive extension for
UIScrollView
:scrollsToTop
. (#3481, kudos to @Qata)
-
UIButton.reactive.pressed
now reacts to theprimaryActionTriggered
control event, instead oftouchUpInside
, on iOS 9.0+ and tvOS 9.0+. (#3480, kudos to @andrei-kuzma) -
New reactive extension:
UITextField.reactive.selectedRangeValues
. (#3479, kudos to @Igor-Palaguta)
-
UITextField text signals now react to
editingDidEndOnExit
. (#3474) -
Introduce
mapControlEvents(_:_:)
which is set to replacecontrolEvents(_:_:)
in most cases. (#3472)You should use
mapControlEvents
in general unless the state of the control — e.g.text
,state
— is not concerned. In other words, you should avoid usingmap
on a control event signal to extract the state from the control. -
Resigning first responder when reacting to a
UITextField
signal no longer deadlocks. (#3453, #3472) -
New operator:
take(duringLifetimeOf:)
. (#3466, kudos to @andersio) It is available onSignal
andSignalProducer
, and supports both Objective-C and native Swift objects.
- Repository Split
- Swift 3.0 API Renaming
- New in 5.0: Cocoa Extensions
- Changes in ReactiveSwift 1.0
- Migrating from the ReactiveObjC API
In version 5.0, we split ReactiveCocoa into multiple repositories for reasons explained in the sections below. The following should help you get started with choosing the repositories you require:
If you’re using only the Swift APIs, you can continue to include ReactiveCocoa. You will also need to link against ReactiveSwift, which is now a dependency of ReactiveCocoa.
If you’re using only the Objective-C APIs, you can switch to using ReactiveObjC. It has all the Obj-C code from RAC 2.
If you’re using both the Swift and Objective-C APIs, you likely require both ReactiveCocoa and ReactiveObjCBridge, which depend on ReactiveSwift and ReactiveObjC.
Attention: If you're using ReactiveCocoa, you'll most likely need to import ReactiveSwift as well when using classes or operators that are implemented in ReactiveSwift.
The ReactiveCocoa library is newly focused on Swift and the UI layers of Apple’s platforms, building on the work of Rex.
Reactive programming provides significant benefit in UI programming. RAC 3 and 4 focused on building out the new core Swift API. But we feel that those APIs have matured and it’s time for RAC-friendly extensions to AppKit and UIKit.
The core, platform-independent Swift APIs have been extracted to a new framework, ReactiveSwift.
As Swift continues to grow as a language and a platform, we hope that it will expand beyond Cocoa and Apple’s platforms. Separating the Swift code makes it possible to use the reactive paradigm on other platforms.
The 3.x and 4.x releases of ReactiveCocoa included the Objective-C code from ReactiveCocoa 2.x. That code has been moved to ReactiveObjC because:
- It’s independent of the Swift code
- It has a separate user base
- It has a separate group of maintainers
We hope that this move will enable continued support of ReactiveObjC.
Moving the Swift and Objective-C APIs to separate repositories meant that a new home was needed for the bridging layer between the two.
This bridge is an important tool for users that are working in mixed-language code bases. Whether you are slowly adding Swift to a mature product built with the ReactiveCocoa Objective-C APIs, or looking to adopt ReactiveCocoa in a mixed code base, the bridge is required to communicate between Swift and Objective-C code.
We mostly adjusted the ReactiveCocoa API to follow the Swift 3 API Design Guidelines, or to match the Cocoa and Foundation API changes that came with Swift 3 and the latest platform SDKs.
Lots has changed, but if you're already migrating to Swift 3 then that should not come as a surprise. Fortunately for you, we've provided annotations in the source that should help you while using the Swift 3 migration tool that ships with Xcode 8. When changes aren't picked up by the migrator, they are often provided for you as Fix-Its.
Tip: You can apply all the suggested fix-its in the current scope by choosing Editor > Fix All In Scope from the main menu in Xcode, or by using the associated keyboard shortcut.
RAC 5.0 includes a few object interception tools from ReactiveObjC, remastered for ReactiveSwift.
-
Method Call Interception
Create signals that are sourced by intercepting Objective-C objects.
// Notify after every time `viewWillAppear(_:)` is called. let appearing = viewController.reactive.trigger(for: #selector(UIViewController.viewWillAppear(_:)))
-
Object Lifetime
Obtain a
Lifetime
token for anyNSObject
to observe their deinitialization.// Observe the lifetime of `object`. object.reactive.lifetime.ended.observeCompleted(doCleanup)
-
Expressive, Safe Key Path Observation
Establish key-value observations in the form of
SignalProducer
s and strong-typedDynamicProperty
s, and enjoy the inherited composability.// A producer that sends the current value of `keyPath`, followed by // subsequent changes. // // Terminate the KVO observation if the lifetime of `self` ends. let producer = object.reactive.values(forKeyPath: #keyPath(key)) .take(during: self.reactive.lifetime) // A parameterized property that represents the supplied key path of the // wrapped object. It holds a weak reference to the wrapped object. let property = DynamicProperty<String>(object: person, keyPath: #keyPath(person.name))
These are accessible via the reactive
magic property that is available on any ObjC objects.
UI components now expose a collection of binding targets to which can be bound from any arbitrary streams of values.
-
UI Bindings
UI components exposes
BindingTarget
s, which accept bindings from any kind of streams of values via the<~
operator.// Bind the `name` property of `person` to the text value of an `UILabel`. nameLabel.reactive.text <~ person.name
-
Controls and User Interactions
Interactive UI components expose
Signal
s for control events and updates in the control value upon user interactions.A selected set of controls provide a convenience, expressive binding API for
Action
s.// Update `allowsCookies` whenever the toggle is flipped. preferences.allowsCookies <~ toggle.reactive.isOnValues // Compute live character counts from the continuous stream of user initiated // changes in the text. textField.reactive.continuousTextValues.map { $0.characters.count } // Trigger `commit` whenever the button is pressed. button.reactive.pressed = CocoaAction(viewModel.commit)
These are accessible via the reactive
magic property that is available on any ObjC objects.
Prior to RAC 5.0, Signal
s lived and continued to emit values (and side effects) until they completed. This was very confusing, even for RAC veterans. So changes have been made to the lifetime semantics. Signal
s now live and continue to emit events only while either (a) they have observers or (b) they are retained. This clears up a number of unexpected cases and makes Signal
s much less dangerous.
Consider using Signal.pipe
for buffer(0)
, MutableProperty
for buffer(1)
or replayLazily(upTo: n)
for buffer(n)
.
Properties are now composable! They have many of the same operators as Signal
and SignalProducer
: map
, filter
, combineLatest
, zip
, flatten
, etc.
Composed properties, including those created via Property(initial:then:)
, are semantically a view to their ultimate sources. In other words, the lifetime, the signal and the producer would respect the ultimate sources, and deinitialization of an instance of composed property would not have an effect on these.
let property = MutableProperty(1)
var composed: Property<Int> = property.map { $0 + 10 }
composed.startWithValues { print("\($0)") }
composed = nil
property.value = 2
// The produced signal is still alive, printing `12` to the output stream.
Atomic.modify
now passes its value to the supplied action as an inout
. This enables the compiler to optimize it as an in-place mutation, which benefits collections, large struct
s and struct
s with considerable amount of references.
Moreover, Atomic.modify
now returns the returned value from the supplied action, instead of the old value as in RAC 4.x, so as to reduce unnecessary copying.
// ReactiveCocoa 4.0
let old = atomicCount.modify { $0 + 1 }
// ReactiveSwift 1.0
let old = atomicCount.modify { value in
let old = value
value += 1
return old
}
The new BindingTargetProtocol
protocol has been formally introduced to represent an entity to which can form a unidirectional binding using the <~
operator. A new type BindingTarget
has also been introduced to represent non-observable targets that are expected to only be written to.
// The `UIControl` exposes a `isEnabled` binding target.
control.isEnabled <~ viewModel.isEnabled
Lifetime
is introduced to represent the lifetime of any arbitrary reference types. It works by completing the signal when its wrapping Lifetime.Token
deinitializes with the associated reference type. While it is provided as NSObject.reactive.lifetime
on Objective-C objects, it can also be associated manually with Swift classes to provide the same semantics.
public final class MyController {
private let token = Lifetime.Token()
public let lifetime: Lifetime
public init() {
lifetime = Lifetime(token)
}
}
ReactiveObjC | ReactiveCocoa 5.0 |
---|---|
Cold RACSignal |
SignalProducer |
Hot RACSignal |
Signal |
Serial RACCommand |
Action |
Concurrent RACCommand |
Currently no counterpart. |
ReactiveObjC | ReactiveCocoa 5.0 |
---|---|
RAC(label, text) |
Discover binding targets via .reactive on UI components.
label.reactive.text <~ viewModel.name |
RACObserve(object, keyPath) |
NSObject.reactive.values(forKeyPath:) |
ReactiveObjC | ReactiveCocoa 5.0 |
---|---|
rac_willDeallocSignal |
NSObject.reactive.lifetime , in conjunction with the take(during:) operator.
signal.take(during: object.reactive.lifetime) |
rac_liftSelector:withSignals: |
Apply combineLatest to your signals, and invoke the method in observeValues .
Signal.combineLatest(signal1, signal2)
.take(during: self.reactive.lifetime)
.observeValues { [weak self] in self?.perform(first: $0, second: $1) } |
rac_signalForSelector: |
NSObject.reactive.trigger(for:) and NSObject.reactive.signal(for:) |
rac_signalForSelector:fromProtocol: |
Currently no counterpart. |
ReactiveObjC | ReactiveCocoa 5.0 |
---|---|
Control value changes, e.g. textField.rac_textSignal() |
Discover control value `Signal`s via .reactive on UI components.
viewModel.searchString <~ textField.reactive.textValues |
rac_signalForControlEvents: |
UIControl.reactive.trigger(for:) |
rac_command |
Discover action binding APIs via .reactive on UI components.
button.reactive.pressed = CocoaAction(viewModel.submitAction) |
If you’re new to the Swift API and migrating from RAC 2, start with the 3.0 changes. This section only covers the differences between 3.0
and 4.0
.
Just like in RAC 3
, because Objective-C is still in widespread use, 99% of RAC 2.x
code will continue to work under RAC 4.0
without any changes. That is, RAC 2.x
primitives are still available in RAC 4.0
.
ReactiveCocoa 4.0
targets Xcode 7.2.x and Swift 2.1.x, and it supports iOS 8.0
, watchOS 2.0
, tvOS 9.0
and OS X 10.9
.
The biggest change from RAC 3
to RAC 4
is that Signal
and SignalProducer
operators are implemented as protocol extensions instead of global functions. This is similar to many of the collection protocol changes in the Swift 2
standard
library.
This enables chaining signal operators with normal dot-method calling syntax, which makes autocompleting operators a lot easier.
Previously the custom |>
was required to enable chaining global functions without a mess of nested calls and parenthesis.
/// RAC 3
signal
|> filter { $0 % 2 == 0 }
|> map { $0 * $0 }
|> observe { print($0) }
/// RAC 4
signal
.filter { $0 % 2 == 0 }
.map { $0 * $0 }
.observeNext { print($0) }
Additionally, this means that SignalProducer
operators are less “magic”. In RAC 3 the Signal
operators were implicitly lifted to work on SignalProducer
via |>
. This was a point of confusion for some, especially when browsing the
source looking for these operators. Now as protocol extensions, the SignalProducer
operators are explicitly implemented in terms of their Signal
counterpart when available.
As already alluded to above, the custom |>
operator for chaining signals has been removed. Instead standard method calling syntax is used for chaining operators.
The improvements to associated enum values in Swift 2
mean that Event
case no longer need to be Box
ed. In fact, the Box
dependency has been removed completely from RAC 4
.
The observe
and start
overloads taking next
, error
, etc. optional function parameters have been removed. They’ve been replaced with methods taking a single function with
the target Event
case — observeNext
, startWithNext
, and the same for failed
and completed
. See #2311 and #2318 for more details.
The try
and catch
operators were renamed because of the addition of the error handling keywords with the same name. They are now attempt
and flatMapError
respectively. Also, tryMap
was renamed to attemptMap
for consistency.
This fills a gap that was missing in RAC 3
. It’s a common pattern to have signals-of-signals or signals-of-producers.
The addition of flatten
and flatMap
over these makes it now possible to work with any combination of Signal
s and SignalProducer
s.
The Error
case of Event
has changed to Failed
. This aims to help clarify the terminating nature of failure/error events and puts them in the same tense as other terminating cases (Interrupted
and Completed
). Likewise, some operations and parameters have been renamed (e.g. Signal.observeError
is now Signal.observeFailed
, Observer.sendError
is now Observer.sendFailed
).
The generic parameters of Signal
, SignalProducer
, and other related types
have been renamed to Value
and Error
from T
and E
respectively. This
is in-line with changes to the standard library to give more descriptive names
to type parameters for increased clarity. This should have limited impact,
only affecting generic, custom signal/producer extensions.
There were some Signal
operators that were missing SignalProducer
equivalents:
takeUntil
combineLatestWith
sampleOn
takeUntilReplacement
zipWith
Signal.on
.Signal.merge(signals:)
.Signal.empty
.skipUntil
.replayLazily
(#2639).
This is in-line with changes to the standard library in Swift 2
.
MutableProperty
received 3 new methods, similar to those in Atomic
: modify
, swap
, and withValue
.
Additionally, all PropertyType
s now have a signal: Signal<T>
in addition to their existing producer: SignalProducer<T>
property.
Bag
and Atomic
are now public. These are useful when creating custom operators for RAC types.
In order to force users to think about the desired capacity, this no longer defaults to Int.max
. Prior to this change one could have inadvertently cached every value emitted by the SignalProducer
. This needs to be specified manually now.
It’s still recommended to use SignalProducer.buffer
or PropertyType
when buffering behavior is desired. However, when you need to compose an existing SignalProducer
to avoid duplicate side effects, this operator is now available.
The full semantics of the operator are documented in the code, and you can see #2639 for full details.
ReactiveCocoa 3.0 includes the first official Swift API, which is intended to eventually supplant the Objective-C API entirely.
However, because migration is hard and time-consuming, and because Objective-C is still in widespread use, 99% of RAC 2.x code will continue to work under RAC 3.0 without any changes.
Since the 3.0 changes are entirely additive, this document will discuss how concepts from the Objective-C API map to the Swift API. For a complete diff of all changes, see the 3.0 pull request.
- Hot signals are now Signals
- Cold signals are now SignalProducers
- Commands are now Actions
- Flattening/merging, concatenating, and switching are now one operator
- Using PropertyType instead of RACObserve and RAC
- Using Signal.pipe instead of RACSubject
- Using SignalProducer.buffer instead of replaying
- Using startWithSignal instead of multicasting
Thanks to Swift, it is now possible to express the type of value that a signal can send. RAC also requires that the type of errors be specified.
For example, Signal<Int, NSError>
is a signal that may send zero or more
integers, and which may send an error of type NSError
.
If it is impossible for a signal to error out, use the built-in
NoError
type
(which can be referred to, but never created) to represent that
case—for example, Signal<String, NoError>
is a signal that may send zero or
more strings, and which will not send an error under any circumstances.
Together, these additions make it much simpler to reason about signal interactions, and protect against several kinds of common bugs that occurred in Objective-C.
In addition to the Next
, Error
, and Completed
events that have always been
part of RAC, version 3.0 adds another terminating
event—called
Interrupted
—that is used to communicate cancellation.
Now, whenever a producer is disposed
of, one final Interrupted
event will be sent to all consumers, giving them
a chance to react to the cancellation.
Similarly, observing a hot signal that has
already terminated will immediately result in an Interrupted
event, to clearly
indicate that no further events are possible.
This brings disposal semantics more in line with normal event delivery, where events propagate downstream from producers to consumers. The result is a simpler model for reasoning about non-erroneous, yet unsuccessful, signal terminations.
Note: Custom Signal
and SignalProducer
operators should handle any received
Interrupted
event by forwarding it to their own observers. This ensures that
interruption correctly propagates through the whole signal chain.
To support interoperation between the Objective-C APIs introduced in RAC 2 and the Swift APIs introduced in RAC 3, the framework offers bridging functions that can convert types back and forth between the two.
Because the APIs are based on fundamentally different designs, the conversion is not always one-to-one; however, every attempt has been made to faithfully translate the concepts between the two APIs (and languages).
Common conversions include:
- The
RACSignal.toSignalProducer
method †- Converts
RACSignal *
toSignalProducer<AnyObject?, NSError>
- Converts
- The
toRACSignal()
function- Converts
SignalProducer<AnyObject?, ErrorType>
toRACSignal *
- Converts
Signal<AnyObject?, ErrorType>
toRACSignal *
- Converts
- The
RACCommand.toAction
method ‡- Converts
RACCommand *
toAction<AnyObject?, AnyObject?, NSError>
- Converts
- The
toRACCommand
function ‡- Converts
Action<AnyObject?, AnyObject?, ErrorType>
toRACCommand *
- Converts
† It is not possible (in the general case) to convert arbitrary RACSignal
instances to Signal
s, because any RACSignal
subscription could potentially
involve side effects. To obtain a Signal
, use RACSignal.toSignalProducer
followed by SignalProducer.start
, thereby making those side effects explicit.
‡ Unfortunately, the executing
properties of actions and commands are not
synchronized across the API bridge. To ensure consistency, only observe the
executing
property from the base object (the one passed into the bridge, not
retrieved from it), so updates occur no matter which object is used for
execution.
In the terminology of RAC 2, a “hot” RACSignal
does not trigger any side effects
when a -subscribe…
method is called upon it. In other words, hot signals are
entirely producer-driven and push-based, and consumers (subscribers) cannot have
any effect on their lifetime.
This pattern is useful for notifying observers about events that will occur no
matter what. For example, a loading
boolean might flip between true and false
regardless of whether anything is observing it.
Concretely, every RACSubject
is a kind of hot signal, because the events
being forwarded are not determined by the number of subscribers on the subject.
In RAC 3, “hot” signals are now solely represented by the
Signal
class, and “cold” signals have been
separated into their own type. This
reduces complexity by making it clear that no Signal
object can trigger side
effects when observed.
In the terminology of RAC 2, a “cold” RACSignal
performs its work one time for
every subscription. In other words, cold signals perform side effects when
a -subscribe…
method is called upon them, and may be able to cancel
in-progress work if -dispose
is called upon the returned RACDisposable
.
This pattern is broadly useful because it minimizes unnecessary work, and
allows operators like take
, retry
, concat
, etc. to manipulate when work is
started and cancelled. Cold signals are also similar to how futures and
promises work, and can be
useful for structuring asynchronous code (like network requests).
In RAC 3, “cold” signals are now solely represented by the
SignalProducer
class, which
clearly indicates their relationship to “hot”
signals. As the name indicates, a signal
producer is responsible for creating
a signal (when started), and can
perform work as part of that process—meanwhile, the signal can have any number
of observers without any additional side effects.
Instead of the ambiguously named RACCommand
, the Swift API offers the
Action
type—named as such because it’s
mainly useful in UI programming—to fulfill the same purpose.
Like the rest of the Swift API, actions are parameterized by the types they use. An action must indicate the type of input it accepts, the type of output it produces, and what kinds of errors can occur (if any). This eliminates a few classes of type error, and clarifies intention.
Actions are also intended to be simpler overall than their predecessor:
- Unlike commands, actions are not bound to or dependent upon the main thread, making it easier to reason about when they can be executed and when they will generate notifications.
- Actions also only support serial execution, because concurrent execution
was a rarely used feature of
RACCommand
that added significant complexity to the interface and implementation.
Because actions are frequently used in conjunction with AppKit or UIKit, there
is also a CocoaAction
class that erases the type parameters of an Action
,
allowing it to be used from Objective-C.
As an example, an action can be wrapped and bound to UIControl
like so:
self.cocoaAction = CocoaAction(underlyingAction)
self.button.addTarget(self.cocoaAction, action: CocoaAction.selector, forControlEvents: UIControlEvents.TouchUpInside)
RAC 2 offers several operators for transforming a signal-of-signals into one
RACSignal
, including:
-flatten
-flattenMap:
+merge:
-concat
+concat:
-switchToLatest
Because -flattenMap:
is the easiest to use, it was often
incorrectly chosen even when concatenation or switching semantics are more
appropriate.
RAC 3 distills these concepts down into just two operators, flatten
and flatMap
.
Note that these do not have the same behavior as -flatten
and -flattenMap:
from RAC 2. Instead, both accept a “strategy” which determines how the
producer-of-producers should be integrated, which can be one of:
.Merge
, which is equivalent to RAC 2’s-flatten
or+merge:
.Concat
, which is equivalent to-concat
or+concat:
.Latest
, which is equivalent to-switchToLatest
This reduces the API surface area, and forces callers to consciously think about which strategy is most appropriate for a given use.
For streams of exactly one value, calls to -flattenMap:
can be replaced with
flatMap(.Concat)
, which has the additional benefit of predictable behavior if
the input stream is refactored to have more values in the future.
To be more Swift-like, RAC 3 de-emphasizes Key-Value Coding (KVC)
and Key-Value Observing (KVO)
in favor of a less “magical” representation for properties.
The PropertyType
protocol and implementations
replace most uses of the RACObserve()
and RAC()
macros.
For example, MutableProperty
can be used to represent a property that can be
bound to. If changes to that property should be visible to consumers, it can
additionally be wrapped in PropertyOf
(to hide the mutable bits) and exposed
publicly.
If KVC or KVO is required by a specific API—for example, to observe changes
to NSOperation.executing
—RAC 3 offers a DynamicProperty
type that can wrap
those key paths. Use this class with caution, though, as it can’t offer any type
safety, and many APIs (especially in AppKit and UIKit) are not documented to be
KVO-compliant.
Since the Signal
type, like RACSubject
, is always “hot”,
there is a special class method for creating a controllable signal. The
Signal.pipe
method can replace the use of subjects, and expresses intent
better by separating the observing API from the sending API.
To use a pipe, set up observers on the signal as desired, then send values to the sink:
let (signal, sink) = Signal<Int, NoError>.pipe()
signal.observe(next: { value in
print(value)
})
// Prints each number
sendNext(sink, 0)
sendNext(sink, 1)
sendNext(sink, 2)
The producer version of
Signal.pipe
,
the SignalProducer.buffer
method can replace replaying with
RACReplaySubject
or any of the -replay…
methods.
Conceptually, buffer
creates a (optionally bounded) queue for events, much
like RACReplaySubject
, and replays those events when new Signal
s are created
from the producer.
For example, to replay the values of an existing Signal
, it just needs to be
fed into the write end of the buffer:
let signal: Signal<Int, NoError>
let (producer, sink) = SignalProducer<Int, NoError>.buffer()
// Saves observed values in the buffer
signal.observe(sink)
// Prints each value buffered
producer.start(next: { value in
print(value)
})
RACMulticastConnection
and the -publish
and -multicast:
operators were
always poorly understood features of RAC 2. In RAC 3, thanks to the Signal
and
SignalProducer
split, the SignalProducer.startWithSignal
method can
replace multicasting.
startWithSignal
allows any number of observers to attach to the created signal
before any work is begun—therefore, the work (and any side effects) still
occurs just once, but the values can be distributed to multiple interested
observers. This fulfills the same purpose of multicasting, in a much clearer and
more tightly-scoped way.
For example:
let producer = timer(5, onScheduler: QueueScheduler.mainQueueScheduler).take(3)
// Starts just one timer, sending the dates to two different observers as they
// are generated.
producer.startWithSignal { signal, disposable in
signal.observe(next: { date in
print(date)
})
signal.observe(someOtherObserver)
}
Disposables haven’t changed much overall in RAC 3, besides the addition of a protocol and minor naming tweaks.
The biggest change to be aware of is that setting
SerialDisposable.innerDisposable
will always dispose of the previous value,
which helps prevent resource leaks or logic errors from forgetting to dispose
manually.
RAC 3 replaces the multipurpose RACScheduler
class with two protocols,
SchedulerType
and DateSchedulerType
, with multiple implementations of each.
This design indicates and enforces the capabilities of each scheduler using the type
system.
In addition, the mainThreadScheduler
has been replaced with UIScheduler
and
QueueScheduler.mainQueueScheduler
. The UIScheduler
type runs operations as
soon as possible on the main thread—even synchronously (if possible), thereby
replacing RAC 2’s -performOnMainThread
operator—while
QueueScheduler.mainQueueScheduler
will always enqueue work after the current
run loop iteration, and can be used to schedule work at a future date.