You can setup a single subscription in init with a PassthroughSubject as a trigger, and .send inside load:

private var cancellables: Set<AnyCancellable> = []
private let loadTrigger = PassthroughSubject<[String: Any], Never>()

init(...) {
   loadTrigger
     //.debounce(...) // possibly debounce load requests
     .flatMap { params in
         WebRepo().index(params: params)
     }
     .sink(
       receiveCompletion: {/* ... */},
       receiveValue: {/* ... */})
     .store(in: &cancellables)
}

func load(params: [String: Any] = [:]) {
    loadTrigger.send(params)
}

I can’t tell you how to handle the error, since it’s very case specific and probably subjective, e.g. should an error terminate the subscription? do you plan to handle possible multiple errors?


If you want to never fail, but still handle an error as a side effect, you can return Result, which would capture both value or error. This way, the pipeline could have a failure type of Never, so it would never terminate due to error. Then you’d unwrap the result inside the .sink:

loadTrigger
   .flatMap { params -> AnyPublisher<Result<MyResponse<[Item]>, Error>, Never> in
       WebRepo().index(params: params)
          .map { .success($0) }
          .catch { Just(.failure($0)) }
          .eraseToAnyPublisher()
   }
   .sink { [weak self] result in
       switch result {
       case success(let response): 
           self?.items = response.data
       case failure(let err):
           // do something with the error
       }
   }

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top