Continuous Streaming With Combine

Combine is a powerful tool to deal with streams in IOS, it keeps streaming data until it either errors out or is told to finish. However in some cases, we do not want the streaming to end when something errors out, this article will show a way to achieve that.

for the GitHub press here

Initial Code

The initial code is nearly simple, we have a class mocking an API that checks if a string is in our "database"(for the sake of simplicity, the "database" is just an array stored in a variable), if the string is present we error out saying we do not want duplicates, otherwise we succeed and add the string to our database.

No alt text provided for this image

We also have our view model where we listen to the stream of incoming names and save them. If the saving of the input is successful we want to tell the user that we succeeded and tell them that it was unsuccessful otherwise.

No alt text provided for this image

Then we have our view that will be the driver of events, we have a text field for users to enter names and a submit button that triggers the saving action.

No alt text provided for this image

let's run this!! Also please don't judge my colour pallet!

Ask you can see it work well until we receive an error because we have a duplicated name. This is because the stream then finished, this would be a really bad user experience! We can fix this thought!

Preventing Stream From Finishing

We know that streams finish when they error out, however, we can catch and handle the error and "tell" the stream to continue. To do this we only need to catch the error return and return it in a Just Publisher and return nil if it is a success:

No alt text provided for this image

In our case we do not expect any object to be returned from our API, in other cases, say your API returns an Object then you could have the mapping and catching return a tuple of (YourObject?, Error?) where the error being not nil would mean a fail and otherwise, the API would have succeeded.

Now we can subscribe to the publisher without excepting an error case, instead, we will always receive a NameError? object and we can handle it like such:

No alt text provided for this image

Notice that we only have a recievedValue case in our subscription, if the error is nil we show a success message and an error message otherwise. Let's try it out!!

As you can see even when we have an error the stream does not finish! Hopefully, this is useful and you learned something :)

you can see the code here in my GitHub.

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics