Combine basics in Swift

Tram Ho

1. Publishers

The first thing you need to understand is that everything in the Combine is Publishers, either operates, or registers the values ​​emitted by Publishers.

Arrays, Strings or Dictionaries can be converted to Publishers in Combine. Can take a simple example as follows.

You register with the publishers by calling sink (receiveValue: (value -> Void)) The approved block will receive all the values ​​generated by that publisher .

Publishers can generate zero or more values ​​throughout their lifetime. Besides the basic values, your Publishers also emit special values ​​represented by the Subscribers.Completion enum.

  • .finished will be issued if registration is over
  • .failure (_) will be emitted if something goes wrong

Relevant values ​​for failure can be Object, Error or Never object indicating that Publishers never generated an error.

If you want to cancel a subscription then you can call cancel () on that subscription.

2. Subjects

Subjects are a gift from Publisher, you can register and manually add elements to it. There are 2 types of subjects in Combine.

  • PassthroughSubject : If you register it, you will receive all events that will occur after you register.
  • CurrentValueSubject : Will give any registrants the most recent element and everything is emitted in that order after the registration occurs.

PassthroughSubject

The first thing we need to do is create an actual PassthroughSubject instance. This is super easy, we can use the default initializer for that.

You can add new elements by using operator send (input: String) . If you want to complete and end the series, you call send (completion: .finished)

Whereas with send (completion: someError) will proceed to add an error in case of an error.

If you register after adding elements to the subject, you will not get those values. You only really get the value when you register in the Subject before you start adding elements.

CurrentValueSubject

Unlike a PassthroughSubject , CurrentValueSubject will receive “World” – String, which is the most recent value. So it works a bit more like an actual variable.

If you read up to this point, then you already know the basics of Combine . There is a lot to learn, but everything is based on these simple rules.

I wish you success with Combine . The article is referenced from here

Share the news now

Source : Viblo