Once we’ve created a publisher, we can then attach subscriptions to it, for example by using the sink API - which lets us pass a closure to be called whenever a new value was received, as well as one that’ll be called once the publisher was completed: let cancellable = publisher. increment call will result in a value being printed: Since we're filtering out all values below 3, only our final With the above in place, we can now subscribe to our new publisher just like we did earlier when performing network requests using URLSession - for example like this: let counter = Counter() We’re using Never as our publisher’s error type, which means that it’ll never be able to throw any errors - which is perfect in this case, since we’re only sending new Int values to it. Note how we’re able to just pass a single closure into our above call to sink, since our publisher can’t throw any errors, which means that we don’t need to handle its completion event (if we don’t want to). However, while the above approach works, it does come with a quite major downside. Since our PassthroughSubject is both a publisher and a subject, any code can send new values to it, even if that code lives outside of our Counter class - simply by calling send(): counter. That isn’t great, as ideally we’d like to enforce that only Counter can send new values - to avoid multiple sources of truth. A subscriber subscribes to the publisher.This is usually done via the sink() method, which allows the programmer to manage both the completion and the values received by the publisher. The publisher creates a subscription and delivers it to the subscriber.The subscriber receives the subscription via the receive(subscription:) method. Now that the subscriber has the subscription and a contract between it and the publisher has been made, it can request for values to the publisher. The subscription receives the demand and starts to process information and emit values.This is done by sending the number of values it wants, by calling request(_:). Those values are sent one by one using the subscriber’s receive(_:) method until the maximum demand is reached.
0 Comments
Leave a Reply. |