Swift Combine: Empty Publisher and replaceEmpty()
Now, let’s take a look at Empty
publisher and replaceEmpty()
operator.
How Empty
Publisher works
let empty = Empty<Int, Never>()
empty
.sink(
receiveCompletion: { print($0) }, //finished
receiveValue: { print($0) } ) // nothing printed
There are some operators which won’t emit any value.
So, let’s go ahead and look at an empty publisher which is actually a part of the combine framework.
The only thing that is going to emit will be the completion event and that’s it.
You might be wondering why you ever need to use an empty transformation operator, and the reason is that sometimes you just don’t want to pass a value.
You just want to say that the task is done and that task has been completed without passing a value.
So in those cases, you can use the empty publisher.
But what if you want to receive a certain value, even when you’re using the empty publisher?
replaceEmpty(with :)
let empty = Empty<Int, Never>()
empty
.replaceEmpty(with: 1)
.sink(
receiveCompletion: { print($0) }, //finished
receiveValue: { print($0) } ) //1
So, in those cases, you can use the don’t replace empty operator and you can replace it with any value.
By using replaceEmpty(with:)
, now you can receive a value that will be printed out.
And then completion block will be finally called.
So, this is how you will use replaceEmpty()
transformation operator.
Conclusion
- Empty Publisher is only used for task completion.
- You can replace empty value with
replaceEmpty()
. - When using Empty Publisher with replaceEmpty(), receiveValue block is called first