This is a cheat sheet for converting from ReactiveSwift to Combine.
The origin of this document is me converting some of my libraries from one to the other, so they’re just basic use cases of things I’ve used. As a result, this sheet by no means exhaustive, but is a good start and includes caveats that go with the transition.
Signal
Signal
instances
This is usually a straightforward find/replace from Signal
to AnyPublisher
. Note: mapping and other such operations on publishers create weird nested types, so you may need to call eraseToAnyPublisher
to trim that down.
observeValues
This is usually a straightforward find/replace from observeValues
to sink.
Signal
class function calls
Find/Replace to Publishers, and capitalize the method you were using (ie Signal.merge becomes Publishers.Merge)
MutableProperty
There are a few ways to do this in Combine.
Subjects
If you want to be able to trigger other behavior based on a value change, you might try either a PassthroughSubject
or a CurrentValueSubject
. These allow you to convert your calls of mutableProperty.value = ...
to subject.send(...)
.
@Published
If you’re interested in storing those values over the longer term, you can simply mark regular properties as @Published
, ie @Published var isEnabled = true
. You can then subscribe to the property by referring to $propName
, ie self.$isEnabled.sink { ... }
. Careful though! When that sink
block is called, the self.isEnabled
won’t have updated yet, so you’ll need to refer to the passed value (or use a non-Combine solution such as didSet
instead).
skipNil
skipNil
is the other one I tended to use a lot in my libraries. By and large I can just replace it with compactMap({ $0 })
, occasionally tacking on eraseToAnyPublisher
.