ReactiveSwift Action in Swift Combine

479 views Asked by At

Is there an alternative to ReactiveSwift Action in Swift Combine? If not, how could it be implemented?

I am not very familiar with Swift Combine yet and could't find it anywhere.

2

There are 2 answers

0
matt On

I'm not familiar with ReactiveSwift, but it looks like an Action is just a custom publisher built from whatever pieces you want. So basically in Combine you would simply build the head of the pipeline in any way you like, and vend that as an AnyPublisher object. But if the question is how to serialize two publishers, so that the second cannot publish until the first has finished, you would use .append or .flatMap (the latter with maxPublishers:.max(1)).

0
Ario Liyan On

So in Combine there isn't such thing as Action in ReactiveSwift but you can leverage the Custom Publishers and create one that does the magic.

For example a basic custom Action publisher can look like this:

import Combine

class Action<Input, Output, Failure: Error> {
      private let work: (Input) -> AnyPublisher<Output, Failure>
      private var cancellables = Set<AnyCancellable>()

      init(work: @escaping (Input) -> AnyPublisher<Output, Failure>) {
          self.work = work
      }

      func execute(input: Input) {
          work(input)
              .sink(receiveCompletion: { completion in
                  switch completion {
                  case .failure(let error):
                      print("Action failed with error: \(error)")
                  case .finished:
                      print("Action completed successfully")
                  }
              }, receiveValue: { value in
                  print("Action produced value: \(value)")
              })
              .store(in: &cancellables)
      }
     }

Here the work closure is where you define what action does. The execute method is used to perform the action with the given input. The result of the action is handled in the sink closure.

This is just a basic implementation and might not cover all the features you need, but you can add those similarly.