Is there a cold/hot signal in swift Combine(likes SignalProducers /Signals in ReactiveCocoa)?

1k Views Asked by At

I recently started using swift's Combine (I've used ReactiveCocoa before), I'm wondering if there is a concept of cold and hot signals also in Combine? Dose Publisher is equal to cold signals(SignalProducers), and No hot signal in Combine? Thanks~

2

There are 2 best solutions below

0
Daniel T. On

A Publisher could be either cold or hot depending on what is backing it. By default though, publishers are cold with specific operators designed to heat them up.

Unlike in ReactiveCocoa, in Combine both hot and cold publishers use the same type.

0
Ario Liyan On

In combine the matter is a little bit more intricate than mere being hot or cold. By default the Apple uses mechanism called backpressure which simply is what we've known as cold flow in Kotlin and other reactive programming. In Swift we have hot publishers like: NotificationCenter.Publisher, and the @Published wrapper in SwiftUI. By default, most publishers in Combine are inherently cold, however there are operators to change a publisher to a hot publisher such as share operator.

   let coldPublisher = Just("Hello, World!")
   let hotPublisher = coldPublisher.share()

The same can be achieved via using Subject publishers too.

 let subject = PassthroughSubject<String, Never>()
 let hotPublisher = subject.eraseToAnyPublisher()
 // Now you can emit values using `subject.send("Hello")`

you can also create your own custom publisher too.

 struct MyHotPublisher: Publisher {
         typealias Output = String
         typealias Failure = Never

         func receive<S>(subscriber: S) where S: Subscriber { 
          // Implement your custom logic here 
         // Emit values to the subscriber 
         }
  }