Swift Combine’s Result.Publisher

Coming from a background in Java/Android development, I’m fairly familiar with working in RxJava and the reactive style of programming. Without getting into the details of said style, there’s a particular operator you can use called Observable.just(), which allows you to wrap a single value in an Observable. This is particularly helpful in tests or mock data where you don’t necessarily have an external source providing the data.

Translating this to Swift, at first glance it seems like the Just operator works just fine. And this is likely the case, unless like one often does with Observables you need to handle error scenarios too, in which case the Result.Publisher is more likely what you’re looking for. Here’s an example: say you’ve got a Publisher that returns a list of Tasks, like for a To-Do list app. Your method to retrieve the Tasks might look something like this:

func getTasks() -> AnyPublisher<[Task], TaskError>

If you wanted to test one of the callers of this method with some mock data, you could do something like this:

Result.Publisher([Task(“Buy Milk”), Task(“Clean garage")])
    .eraseToAnyPublisher()

The .eraseToAnyPublisher() at the end is needed because otherwise this will return a Result. If you then wanted to test handling an error scenario, you’d do something like this:

Result<[Task], TaskError>.Publisher(.failure(TaskError.notFound))
    .eraseToAnyPublisher()

Note that you’ll likely have to explicitly define the type for the Result in this case as the compiler is otherwise unable to determine it.