Modifying publisher in Swift

Xinyi Xiang
1 min readOct 5, 2020

From the documentation, we can see that publisher returns a tuple with data and URL error, the publisher would contain some error types as well. However, by utilizing dataTaskPublisher under URLSession.shared and map the publisher, we can customize the publish type to publish an UIImage optional instead.

This took the same idea as how you can modify Views by addressing modifiers on them, you can approach the publishers in a similar way. Notice that after the modification, the .sink function would not offer an option that only takes a value parameter and for remaining errors, use replaceError(with:nil) for solely publishing the type.

This comes in handy when we need to user .assign in publisher, since it would not perform with any error. You may then assign the var belonging to AnyCancellable optional to what the Publisher assigns. This would not be a let assign as the cancellable assignment when using the .sink function in the projected value.

// Another way to implement the above process
DispatchQueue.global(qos: .userInitiated).async{
if let imageData = try? Data(contentsOf: url) {
DispatchQueue.main.async{
if url == self.emojiArt.backgroundURL{
self.backgroundImage = UIImage(data: imageData)}}}}

Think Further:
To make a preview have a live binding

--

--