<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by N!kunj Joshi on Medium]]></title>
        <description><![CDATA[Stories by N!kunj Joshi on Medium]]></description>
        <link>https://medium.com/@nikunj-joshi?source=rss-4dd996182143------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MiH7wt1ODsBSQt91NB5tzw.jpeg</url>
            <title>Stories by N!kunj Joshi on Medium</title>
            <link>https://medium.com/@nikunj-joshi?source=rss-4dd996182143------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:01:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikunj-joshi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Swift Combine —Transforming Operators]]></title>
            <link>https://nikunj-joshi.medium.com/swift-combine-transforming-operators-9899fc542216?source=rss-4dd996182143------2</link>
            <guid isPermaLink="false">https://medium.com/p/9899fc542216</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[combine-framework]]></category>
            <dc:creator><![CDATA[N!kunj Joshi]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 15:19:05 GMT</pubDate>
            <atom:updated>2023-02-03T15:19:32.053Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous <a href="https://medium.com/@nikunj-joshi/swift-combine-introduction-to-combine-operators-filtering-operators-510d962b95f2"><em>article</em></a>, we have explored various <strong><em>Filtering Operators</em></strong>. <strong><em>Many times you will need to re-format or replace the received event/values from the Publisher into another suitable format / value before passing through to the Subscriber.</em></strong> <strong><em>Transforming Operators </em></strong>helps to achieve this transformation easily.</p><blockquote>If you are directly reading this article, knowledge of <strong>Subscriber</strong>, <strong>Publisher</strong> and <strong>Subject</strong> is a MUST to understand the code of this article. If you wish to revise feel free to revisit the <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0"><strong>learning series</strong></a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VCxyfp2isS6SG9tl" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=medium&amp;utm_medium=referral">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><em>collect()</em> Operator</h4><p><strong><em>Situation </em>: </strong>You are given a task to display all the available Promo Codes as a ListView / TableView. <strong><em>collect() </em></strong>operator helps you to collect all emitted values and emit as as a single array.</p><p><strong><em>Collect()</em></strong> Operator buffers all the values till the Publisher complets and sends it as a single collection to the Subscriber.</p><p><em>Let’s play with some code.</em></p><pre>import Foundation<br>import Combine<br><br>/*<br> <br> This is a Util function for logs.<br> <br> We will use this function to clearly distinguis the examples of variois topics.<br> Function will take a title of the topic and will execute the blocks after printing.<br> */<br>public func myLearningCode(of title: String,<br>                          execute: () -&gt; Void) {<br>    print(&quot;\n ***** Example of:&quot;, title, &quot;***** \n&quot;)<br>    execute()<br>}<br><br>myLearningCode(of: &quot;&#39;collect()&#39; Operator&quot;) {<br>    <br>    let promoCodePublisher = [&quot;Promo 1&quot;, &quot;Promo 2&quot;, &quot;Promo 3&quot;,<br>                              &quot;Promo 4&quot;, &quot;Promo 5&quot;, &quot;Promo 6&quot;].publisher<br>    <br>    promoCodePublisher<br>        .collect()<br>        .sink { completion in<br>            print(&quot;Received a completion: \(completion)&quot;)<br>        } receiveValue: { collection in<br>            print(&quot;Received a collection: \(collection)&quot;)<br>        }<br>}<br><br>myLearningCode(of: &quot;&#39;collect(n)&#39; Operator&quot;) {<br>    <br>    let promoCodePublisher = [&quot;Promo 1&quot;, &quot;Promo 2&quot;, &quot;Promo 3&quot;,<br>                              &quot;Promo 4&quot;, &quot;Promo 5&quot;].publisher<br>    <br>    promoCodePublisher<br>        .collect(2)<br>        .sink { completion in<br>            print(&quot;Received a completion: \(completion)&quot;)<br>        } receiveValue: { collection in<br>            print(&quot;Received a collection: \(collection)&quot;)<br>        }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FM3QC8MwoXgtqiNDW-5dqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*msmUF0PdfQQBDtp7" /><figcaption>Photo by <a href="https://unsplash.com/es/@bmpanaguiton?utm_source=medium&amp;utm_medium=referral">Breana Panaguiton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Beware when using buffering operators like collect() without setting a count or limit. They can consume unlimited memory storing values until the upstream / publisher completes. You can use collect(n) variant as shown above, which will return you collections with count of n.</em></p><h4>map(_:) Operator</h4><p><strong><em>Situation</em></strong> : <em>Remembering you were waiting for your food order number to display at a burger shop? Now, instead of simply showing only order number, you want to display ‘Your Order Number x is ready, Please collect’. </em><strong><em>Map</em></strong><em> operator comes to your rescue for mapping one type of event / values to the another one as per your convenience.</em></p><p>Map operator has some different variants to tackle different scenarios of the mapping incoming events / values.</p><ul><li><strong><em>map(_:) =&gt; </em></strong>Used to map values / events to other format as per convenience<strong><em>.</em></strong></li><li><strong><em>map&lt;T&gt;(_:)</em></strong> , <strong>map&lt;T0, T1&gt;(_:_:)</strong> , <strong>map&lt;T0, T1, T2&gt;(_:_:_:)</strong> =&gt; Works same as a <strong><em>map </em></strong>operator.<em> Only difference is, you can directly map object properties using keypath (e.g. Published Properties) of the received object event.</em></li><li><strong>tryMap(_:) =&gt; </strong>There will may be a case where you want to map upcoming value to the different one but It can generate an error while formatting the upcoming value. <strong><em>tryMap </em></strong><em>gives an failure completion in case of the error generated while mapping.</em></li><li><strong>flatMap<em>(_:)</em></strong> , <strong>flatMap(maxPublishers:_:) =&gt; </strong>It is used to flatten all the Publishers to a single Publisher after mapping. Let’s say you are passing an received event to other function which is returning you a Publisher. In this case, normal <strong><em>map </em></strong>operator will result into array of the mapped Publishers returned by your function. <strong>flatMap </strong>will help you to convert <em>received array of the mapped Publishers to an array with actual values / events. ‘</em><strong><em>maxPublishers</em>’ </strong>variant will help to limit active publishers at any particular time to the specified one.</li></ul><p><em>Let’s see some magic via code.</em></p><pre>myLearningCode(of: &quot;&#39;map&#39; Operator&quot;) {<br>    <br>    let orderNumberPublisher = (45...50).publisher<br>    <br>    orderNumberPublisher.map { preparedOrder in<br>        &quot;Your Order Number \(preparedOrder) is ready, Please collect&#39;&quot;<br>    }.sink { completion in<br>        print(&quot;Received a completion: \(completion)&quot;)<br>    } receiveValue: { receivedValue in<br>        print(&quot;Received a value: \(receivedValue)&quot;)<br>    }<br>    <br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0r1ajlfTfwMriUsf_To_Ew.png" /></figure><p>👇👇👇 <em>Code</em> 👇👇👇</p><pre>myLearningCode(of: &quot;&#39;map&lt;T0, T1&gt;(_:_:)&#39; Operator&quot;) {<br>    <br>    struct BankBalance {<br>        let currentBalace: Double<br>        let currentIntrestRate: Double<br>    }<br>    <br>    let bankBalancePublisher = PassthroughSubject&lt;BankBalance, Never&gt;()<br>    <br>    bankBalancePublisher<br>        .map(\.currentBalace, \.currentIntrestRate)<br>        .sink { completion in<br>            print(&quot;Received a completion: \(completion)&quot;)<br>        } receiveValue: { balance, interest in<br>            print(&quot;Balance is: \(balance), Interest: \(interest)&quot;)<br>        }<br><br>    bankBalancePublisher.send(.init(currentBalace: 10000, currentIntrestRate: 15))<br>    bankBalancePublisher.send(completion: .finished)<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zCL6WY7lXjShSN4yykUug.png" /></figure><p>👇👇👇 <em>Code</em> 👇👇👇</p><pre>myLearningCode(of: &quot;&#39;tryMap&#39; Operator&quot;) {<br>    <br>    let unknownFileError = [&quot;filePathThatDoesnotExists&quot;].publisher<br>    <br>    unknownFileError.tryMap { receivedValue in<br>        try FileManager<br>            .default<br>            .contentsOfDirectory(atPath: receivedValue)<br>    }.sink { completion in<br>        print(&quot;Received a completion: \(completion)&quot;)<br>    } receiveValue: { value in<br>        print(&quot;Received a file: \(value)&quot;)<br>    }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxi1ut6ZOw1bgyydx5QmTQ.png" /></figure><p>👇👇👇 <em>Code</em> 👇👇👇</p><pre>myLearningCode(of: &quot;&#39;flatMap&#39; Operator&quot;) {<br>    <br>    func bulkOrderNumbersToString(orderNums: [Int]) -&gt; AnyPublisher&lt;String, Never&gt; {<br>        print(#function)<br>        var outputMessage = &quot;Ready Orders are: &quot;<br>        orderNums.forEach { order in<br>            outputMessage = outputMessage + &quot;\(order), &quot;<br>        }<br>        let pub = Just(outputMessage).eraseToAnyPublisher()<br>        print(&quot;Printing the returning Publisher \n&quot;)<br>        dump(pub)<br>        print(&quot;Returning a Publisher with a String value\n \n&quot;)<br>        return pub<br>    }<br>    <br>    _ = (45...50).publisher<br>        .collect()<br>        .flatMap(bulkOrderNumbersToString)<br>        .sink { completion in<br>            print(&quot;Received a completion: \(completion)&quot;)<br>        } receiveValue: { receivedValue in<br>            print(&quot;Instead of getting Publisher from &#39;bulkOrderNumberToString&#39;, \nwe are getting a string as an event, \nbcz &#39;flatMap&#39; has flattned the result from AnyPublisher to the underlying value \n&quot;)<br>            print(&quot;Received a value: \(receivedValue)&quot;)<br>        }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Vnf8aGtWh6TbxRDMiv2sg.png" /></figure><h4>replaceNil(with:)</h4><p><strong><em>Situation </em>: </strong>As its name suggests, this operator helps you to replace all the occurrences of the <em>‘nil’ </em>values with the specified value. This is an equivalent to the <strong><em>nil-coalescing operator (??</em>) </strong>of the swift, but <em>this operator ensures that no nil can be returned unlike nil-coalescing operator.</em></p><pre>myLearningCode(of: &quot;&#39;replaceNil(with:)&#39; Operator&quot;) {<br>    <br>    _ = [&quot;value 1&quot;, nil, &quot;value 2&quot;, &quot;value 3&quot;].publisher<br>        .eraseToAnyPublisher()<br>        .replaceNil(with: &quot;###&quot;)<br>        .sink { completion in<br>            print(&quot;Received a completion: \(completion)&quot;)<br>        } receiveValue: { receivedValue in<br>            print(&quot;Received a value: \(receivedValue)&quot;)<br>        }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4vPaf3we7XdnOMT4mrZJg.png" /></figure><h4>replaceEmpty(with:) Operator</h4><p><strong><em>Situation </em>: </strong>Again easy one!!!, this operator helps you to replace empty value with the specified value. It can be the case where your publisher emits a completion event without sending any event / value. (e.g. Empty Publisher)</p><pre>myLearningCode(of: &quot;&#39;replaceEmpty(with:)&#39; Operator&quot;) {<br>    <br>    let emptyPublisher = Empty&lt;Int, Never&gt;()<br>    <br>    _ = emptyPublisher<br>        .replaceEmpty(with: 2023)<br>        .sink { completion in<br>            print(&quot;Received a completion: \(completion)&quot;)<br>        } receiveValue: { receivedValue in<br>            print(&quot;Received a value: \(receivedValue)&quot;)<br>        }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Y33tpph5R2uJZQjlNgeXA.png" /></figure><p><strong><em>compactMap Operator</em></strong></p><p><strong><em>Situation </em>: </strong>There is an operator which does work of both <strong><em>Filtering all nil values + Mapping it to the asked format </em></strong>— called <strong><em>compactMap</em></strong>. Let’s understand it using ‘<em>replaceNil</em>’ operator’s example code only.</p><pre>myLearningCode(of: &quot;&#39;compactMap&#39; Operator&quot;) {<br>    <br>    <br>    _ = [&quot;value 1&quot;, nil, &quot;value 2&quot;, &quot;value 3&quot;].publisher<br>        .eraseToAnyPublisher()<br>        .compactMap({ receivedValue in<br>            receivedValue<br>        })<br>        .sink { completion in<br>            print(&quot;Received a completion: \(completion)&quot;)<br>        } receiveValue: { receivedValue in<br>            print(&quot;Received at Sink from compactMap: \(receivedValue)&quot;)<br>        }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-dlu5vac1QycLG6J7XP9Q.png" /></figure><h4>scan(_:_:) Operator</h4><p><strong><em>Situation</em></strong> : <em>You are working on a ‘WeightLoss’ application and you want to give a feature to monitor Calorie gain for a streak of 10 days. Conventional way of calculating final result of 10 days is like: you will hold one variable with initial / current value and add up daily calorie values to it till last day. Combine provides you </em><strong><em>scan </em></strong><em>operator which does exactly same for you. This is equivalent to ‘reduce’ operator of swift language. </em><strong><em>scan </em></strong><em>operator takes an initial value, manipulate it with each emitted value as per the specified logic and emits the updated one.</em></p><pre>myLearningCode(of: &quot;&#39;scan&#39; Operator&quot;) {<br>    <br>    let dailyCaloriePublisher = [500, 800, 200, -1000, 240, 490, 1500].publisher<br>    <br>    _ = dailyCaloriePublisher.scan(0, { totalCalorieTillDate, todayCalorie in<br>        totalCalorieTillDate + todayCalorie<br>    }).sink { completion in<br>        print(&quot;Received a completion: \(completion)&quot;)<br>    } receiveValue: { receivedValue in<br>        print(&quot;Net calorie gain is: \(receivedValue)&quot;)<br>    }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRABPmhV7dVotcylTP72oQ.png" /></figure><p><em>If you expand the ‘show result’ button in playground sidebar for our ‘scan’ operator closure calculation, you will see something like below:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWS9CB_o7KxTHTCapw10zg.png" /></figure><p>In this article, We have explored <strong><em>Transforming Operators</em></strong> of combine. We will deep dive into another exciting type of the Operators : <strong><em>Combining Operators</em></strong>. Stay tuned with the combine <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><p>Feel free to <a href="https://nikunj-joshi.medium.com/"><strong>follow me</strong></a> to stay updated with the upcoming articles.</p><p>Thank You. Cheers!</p><p><strong>#Pre-Requisite<br></strong><em>Intermediate level of the swift language / iOS is required for this Combine Article series.</em></p><p><strong>#Credits</strong></p><p><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9899fc542216" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Combine — Introduction to Combine Operators, Filtering Operators]]></title>
            <link>https://nikunj-joshi.medium.com/swift-combine-introduction-to-combine-operators-filtering-operators-510d962b95f2?source=rss-4dd996182143------2</link>
            <guid isPermaLink="false">https://medium.com/p/510d962b95f2</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[combine-framework]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[N!kunj Joshi]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 19:28:37 GMT</pubDate>
            <atom:updated>2023-01-30T19:32:22.099Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Combine — Combine <em>Operators &amp; </em>Filtering Operators</h3><p>Till now, in our <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0"><em>learning series</em></a>, we got familiar with <strong><em>Publisher</em></strong> and <strong><em>Subscriber</em></strong>. <em>It’s high time to explore a component which makes combine very interesting by giving many functionalities to manipulate events between a Publisher and Subscriber/s </em><strong><em>— Operators</em></strong>.</p><blockquote><em>If you are directly reading this article, knowledge of </em><strong>Subscriber</strong><em>, </em><strong>Publisher</strong><em> and </em><strong>Subject</strong><em> is a MUST to understand the code of this article. If you wish to revise feel free to revisit the </em><a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0"><strong>learning series</strong></a><em>.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XqUXeHyRNE8ZtOVf" /><figcaption>Photo by <a href="https://unsplash.com/@dancristianpaduret?utm_source=medium&amp;utm_medium=referral">Dan Cristian Pădureț</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Combine refers to <em>methods performing operations on publisher values</em> as “<strong><em>Operators</em></strong>”. <strong><em>Operators</em></strong> in Combine typically produce a publisher that processes incoming events, transforms them, and then emits the altered events to subscribers / consumers.</p><p>Most of the useful <strong><em>Operators</em></strong> provided by Combine fall into below major categories.</p><ol><li>Filtering : <em>Used to limit or regulate the values or events emitted by the publisher to downstream components.</em></li><li>Transforming :<em> Used to manipulate or reformat the upcoming events / publishers in another needful format for further subscribers / consumers.</em></li><li>Combining : <em>Useful when we want to combine events from different Publishers and combine them into other meaningful state for our combine logic flow.</em></li><li>Time Manipulation : <em>As name suggest, this category helps us to decide how our event sequence will react with respect to Time</em>.</li><li>Sequence : <em>This category differs a bit from other as this category deals with </em><strong><em>Publisher as a whole sequence</em></strong><em> instead of on each separate event. This operators are very handy with the publishers with a finite number of the events.</em></li></ol><blockquote>If you are familiar with Higher Order Functions in Swift, this operators will very easy to understand.</blockquote><h3>Filtering Operators</h3><p>Sometimes subscriber doesn’t need to utilize all the events emitted by the <strong><em>Publisher</em></strong> and only wants to consume some of them, <strong><em>Filtering Operators</em></strong><em> helps to achieve same</em>. <em>Remembering our Burger order example ?? Where you were waiting for your order number to display on the screen? Let’s say your order number is 78 and you really don’t need to listen to all the order status, what you as a subscriber can do is to filter the order number announcement till 75 and then actively monitor the display. Sounds familiar, right?</em></p><p><em>Code speaks louder than these sentences. We will learn by Example situation for each operator. </em>Let’s explore some <strong><em>Filtering</em></strong> Operators with code.</p><h4>Filter Operator</h4><p><strong><em>Situation</em></strong> : <em>You are designing a Loan Processing Application where you want to send users for further check only if Credit score of the user is greater than 706, here, </em><strong><em>Filter</em></strong><em> operator comes handy.</em></p><pre>import Foundation<br>import Combine<br><br>/*<br> <br> This is a Util function for logs.<br> <br> We will use this function to clearly distinguis the examples of variois topics.<br> Function will take a title of the topic and will execute the blocks after printing.<br> */<br>public func myLearningCode(of title: String,<br>                          execute: () -&gt; Void) {<br>    print(&quot;\n ***** Example of:&quot;, title, &quot;***** \n&quot;)<br>    execute()<br>}<br><br>myLearningCode(of: &quot;Filter Operator&quot;) {<br>    <br>    let creditScorePublisher = [304, 850, 900, 704, 605, 455].publisher<br>    <br>    creditScorePublisher<br>        .filter { currentCreditScore in<br>            currentCreditScore &gt; 706<br>        }.sink { receivedValue in<br>            print(&quot;Eligible for a Loan with credit score \(receivedValue)&quot;)<br>        }<br>}</pre><p><strong><em>Output</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnDBmgLWYvChigMAAADDPA.png" /></figure><h4>removeDuplicates Operator</h4><p><strong><em>Situation</em></strong> : <em>Sometimes subscriber doesn’t want to process identical event values received in a row. </em><strong><em>removeDuplicates</em></strong><em> helps to exclude an event if it is identical to the previous one.</em></p><pre>myLearningCode(of: &quot;removeDuplicates Operator&quot;) {<br>    <br>    let receivedValues = [&quot;Perceptia&quot;, &quot;Wanderie&quot;, &quot;Wanderie&quot;, &quot;9Yardly&quot;].publisher<br>    <br>    receivedValues<br>        .removeDuplicates()<br>        .sink { receivedName in<br>            print(&quot;How&#39;s this unique name? : \(receivedName)&quot;)<br>        }<br>}</pre><p><strong><em>Output</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2uYok1h1XB6SOONrSIAzw.png" /></figure><p>Remember, <em>this operator doesn’t process Publisher as a whole set, instead it only process on a received value at particular time.</em> So if there are duplicate events but not received in sequence, they will not be removed by this operator.</p><p><em>Let’s alter above code and see.</em></p><pre>myLearningCode(of: &quot;removeDuplicates Operator&quot;) {<br>    <br>    let receivedValues = [&quot;Perceptia&quot;, &quot;Wanderie&quot;, &quot;Wanderie&quot;,<br>                          &quot;9Yardly&quot;, &quot;Perceptia&quot;, &quot;Wanderie&quot;].publisher    <br>    receivedValues<br>        .removeDuplicates()<br>        .sink { receivedName in<br>            print(&quot;How&#39;s this unique name? : \(receivedName)&quot;)<br>        }<br>}</pre><p><strong><em>Output</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFlMB3UrcODLyzJ6t4Pxgw.png" /></figure><h4>ignoreOutput Operator</h4><p><strong>Situation :</strong><em> you have an Onboarding flow in your app with five screens, after that you want to launch the dashboard. For the Dashboard screen launching, only important condition is that Onboarding flow gets completed, you don’t want to bother about events of Onboarding Publisher, you just only want to launch once previous publisher is completed. ‘</em><strong><em>ignoreOutput</em></strong><em>’ operators helps you in this type of situation.</em></p><pre>myLearningCode(of: &quot;ignoreOutput Operator&quot;) {<br>    <br>    let receivedValues = [&quot;Welcome screen 1&quot;, &quot;screen 2&quot;,<br>                          &quot;screen 3&quot;, &quot;screen 4&quot;, &quot;screen 5&quot;].publisher<br>    <br>    receivedValues<br>        .ignoreOutput()<br>        .sink { receivedCompletion in<br>            print(&quot;Received Completion \(receivedCompletion)&quot;)<br>        } receiveValue: { receivedValue in<br>            print(&quot;Received Value \(receivedValue)&quot;)<br>        }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjNOMN56lX6VSVZFXEFLNQ.png" /></figure><h4><em>first(where:)</em> Operator</h4><p><em>Situation : You have rejected many customers with a bad credit score using ‘</em><strong><em>Filter</em></strong><em>’ operator during first example, right? But, your product owner tells you to monitor those customer for the credit score change, once customer becomes eligible with your threshold credit score, you want to approach him/her again. let’s use </em><strong><em>first(where:)</em></strong><em> operator to help you out.</em></p><pre>myLearningCode(of: &quot;&#39;first(where:)&#39; Operator&quot;) {<br>    <br>    let customerCreditScorePublisher = [605, 630, 600, 620,<br>                                        650, 730, 710, 704].publisher<br>    <br>    customerCreditScorePublisher.first { updatedScore in<br>        updatedScore &gt; 706<br>    }.sink { completion in<br>        print(&quot;Received Completion : \(completion)&quot;)<br>    } receiveValue: { value in<br>        print(&quot;Credit score is now &#39;&gt; 706&#39; : \(value)&quot;)<br>    }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWikz9I_aTtvapYV7vPaOw.png" /></figure><p>Observe that, input value i<em>s lowering to 704 which is violating our condition of (&gt;706) after we getting the value 730 but it is not processed</em>. It is because, once condition provided in <strong><em>first(where:)</em></strong> operator is satisfied, that value will be emitted followed by a completion event. <br><em>This Operator is </em><strong><em>lazy</em></strong><em> because when condition is met, it sends that value, cancels the subscription, and completes.</em></p><h4>last(where:) Operator</h4><p>Situation : <em>This operator is an opposite of the </em><strong><em>first(where:) </em></strong><em>operator. Consider same situation as </em><strong><em>first(where:)</em></strong><em> operator but this time you want to detect what is the last credit score of the customer which is lower than allowed threshold limit.</em></p><ul><li>To use <strong><em>last(where:) </em></strong>operator, publisher should have some END for the emitting values. Without determining last emitted value, <em>operator will not able to evaluate given condition</em>. So remember, <strong>Publisher should be a finite event emitter for the <em>last(where:) operator</em>.</strong></li></ul><pre>myLearningCode(of: &quot;&#39;last(where:)&#39; Operator&quot;) {<br>    <br>    let customerCreditScorePublisher = [605, 630, 600, 620,<br>                                        650, 730, 710, 704].publisher<br>       <br>    customerCreditScorePublisher.last { updatedScore in<br>        updatedScore &lt; 706<br>    }.sink { completion in<br>        print(&quot;Received Completion : \(completion)&quot;)<br>    } receiveValue: { value in<br>        print(&quot;Last score which is &#39;&lt; 706&#39; : \(value)&quot;)<br>    }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntXtc-TBF08WWjCMwl7GTg.png" /></figure><p>Try<strong><em> last(where:) </em></strong>operator with <a href="https://medium.com/@nikunj-joshi/swift-combine-subject-publishers-passthroughsubject-currentvaluesubject-52fe7fbe58b8"><em>a Publisher with Infinite events</em></a> without sending a completion and observe the behaviour.</p><h4>dropFirst Operator</h4><p><strong><em>Situation</em></strong> : <em>You have a feature of PIN authentication for the debit card, total allowed wrong attempts are 5 and you want to display of a possible card blocking warning after 3rd failed attempts. Your attempts Publisher is going to send you value each time, but should you really bothered about first three events?</em> <em>NO, right</em>? <strong><em>dropFirst helps you to stay chilled during first 3 failed attempts in this scenario.</em></strong></p><pre>myLearningCode(of: &quot;&#39;dropFirst&#39; Operator&quot;) {<br>    <br>    let retryCountPublisher = (1...5).publisher<br>    <br>    retryCountPublisher<br>        .dropFirst(3)<br>        .sink { completion in<br>            print(&quot;Received Completion : \(completion)&quot;)<br>        } receiveValue: { value in<br>            print(&quot;Show a warning as this is \(value)th attempt&quot;)<br>        }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuD2UARdc795l4cQpcRU5g.png" /></figure><h4>drop(while:) Operator</h4><p><strong><em>Situation</em></strong><em> : You are working on a cricket score display application, and want to give a feature of triggering a notification once a player reach to a century (100 runs). You can use </em><strong><em>drop(while:)</em></strong> <em>operator to ignore all score changes of the player until score is 100 or more. </em><strong><em>You might be thinking that I can also use ‘dropFirst(99)’ on the player’s run publisher, but wait, in that case you will need to inform that player to take only 99 singles to make your code work !:) :)</em></strong></p><pre>myLearningCode(of: &quot;&#39;drop(while:)&#39; Operator&quot;) {<br>    <br>    let scoreChangePublisher = [23, 27, 28, 30, 36,<br>                                91, 97, 99, 104, 110, 140].publisher<br>    <br>    scoreChangePublisher<br>        .drop(while: { currentScore in<br>            print(&quot;evaluating \(currentScore) score using drop(while:) \n&quot;)<br>            return currentScore &lt; 100<br>        })<br>        .sink { completion in<br>            print(&quot;OUT !!!! : \(completion)&quot;)<br>        } receiveValue: { value in<br>            print(&quot;Your favorite player&#39;s score is : \(value) &quot;)<br>        }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ioCkg9sNfMH1tYPoZfCs1A.png" /></figure><p>Wait ! ! ! You might say that c’mon mate, I can achieve same output using <strong><em>filter</em></strong> operator also, then :</p><h4><strong>what is a difference between <em>filter</em> and <em>drop(while:) ?!?</em></strong></h4><ul><li><strong><em>Filter</em></strong> lets <em>value go through subscriber if provided condition is true</em> for the value, <strong><em>drop(while:) </em></strong><em>prevents value to get emitted to subscriber if given condition is true.</em></li><li><strong>Main difference</strong> is that, <strong><em>Filter </em></strong><em>evaluates all the values emitted by the publisher vs </em><strong><em>drop(while:) </em></strong><em>evaluates only until condition is not satisfied first time. </em>If you see above output, score after 104 (where our given condition got violated : 110 and 140) are not sent for the evaluation by the <strong><em>drop(while:) operator</em></strong>.</li></ul><h4>drop(untilOutputFrom:) Operator</h4><p><strong><em>Situation</em></strong> :<em> You have been given a task of developing a calling feature in a chat app. User dial to his/her friend and receiver is busy. You only want to give retry call once the receiver of the previous call is ready to take your call after completing the previous one. Instead of keep checking manually about availability of the receiver, </em><strong><em>drop(untilOutputFrom:)</em></strong><em> is the saviour for this type of scenario.</em></p><pre>var subscriptions = Set&lt;AnyCancellable&gt;()<br><br>myLearningCode(of: &quot;&#39;drop(untilOutputFrom:)&#39; Operator&quot;) {<br>    <br>    let isReceiverReadyPublisher = PassthroughSubject&lt;Void, Never&gt;()<br>    let callingButtonTapsPublisher = PassthroughSubject&lt;Int, Never&gt;()<br>    <br>    callingButtonTapsPublisher<br>        .drop(untilOutputFrom: isReceiverReadyPublisher)<br>        .sink { completion in<br>            print(&quot;Received Completion : \(completion)&quot;)<br>        } receiveValue: { value in<br>            print(&quot;Received value : \(value)&quot;)<br>        }<br>        .store(in: &amp;subscriptions)<br>    <br>    (1...6).forEach { currentTap in<br>        callingButtonTapsPublisher.send(currentTap)<br>        <br>        if currentTap == 3 {<br>            isReceiverReadyPublisher.send()<br>        }<br>    }<br>    callingButtonTapsPublisher.send(completion: .finished)<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMgHItA_6AxPGNsSdIhlVg.png" /></figure><p><em>If you notice, all events are dropped until output from the ‘isReceiverReadyPublisher’ is not received.</em></p><blockquote>If you are not getting the above code of <em>PassthroughSubject, please feel free to revisit this </em><a href="https://medium.com/@nikunj-joshi/swift-combine-subject-publishers-passthroughsubject-currentvaluesubject-52fe7fbe58b8"><em>article</em></a><em>.</em></blockquote><h4>prefix(_:), prefix(while:) &amp; prefix(untilOutputFrom:)</h4><p><strong><em>Situation</em></strong> : These all three operators are exactly opposite of the previous ‘<em>drop</em>’ version of the same operators. Sometimes, <strong>you only want to receive values until some condition is met</strong>. <em>e.g. Want to send promo notifications only until first 10 items are sold or total sale order reaches to 100 crores…</em></p><p>If you are reading these ‘<strong><em>prefix</em></strong>’ operators directly, please go through <strong>dropFirst, drop(while:)</strong> and <strong>drop(untilOutputFrom:) </strong>first.</p><p><em>Let’s change the drop operators to prefix operators in above code examples.</em></p><p><strong><em>prefix</em></strong></p><pre>myLearningCode(of: &quot;&#39;prefix&#39; Operator&quot;) {<br><br>    let retryCountPublisher = (1...5).publisher<br><br>    retryCountPublisher<br>        .prefix(3)<br>        .sink { completion in<br>            print(&quot;Received Completion : \(completion)&quot;)<br>        } receiveValue: { value in<br>            print(&quot;Don&#39;t Show a warning as this is \(value)th attempt&quot;)<br>        }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cek-wjBXf-4e33Kz4qm_IQ.png" /></figure><p><strong><em>prefix(while:)</em></strong></p><pre>myLearningCode(of: &quot;&#39;prefix(while:)&#39; Operator&quot;) {<br><br>    let scoreChangePublisher = [23, 27, 28, 30, 36,<br>                                91, 97, 99, 104, 110, 140].publisher<br><br>    scoreChangePublisher<br>        .prefix(while: { currentScore in<br>            return currentScore &lt; 100<br>        })<br>        .sink { completion in<br>            print(&quot;Received a completion: \(completion)&quot;)<br>        } receiveValue: { value in<br>            print(&quot;Your player&#39;s score \(value) is under 100&quot;)<br>        }<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tfGck6TebYFVr1X4Z6pj6Q.png" /></figure><p><strong>prefix(untilOutputFrom:)</strong></p><pre>var subscriptions = Set&lt;AnyCancellable&gt;()<br><br>myLearningCode(of: &quot;&#39;prefix(untilOutputFrom:)&#39; Operator&quot;) {<br>    <br>    let isReceiverReadyPublisher = PassthroughSubject&lt;Void, Never&gt;()<br>    let callingButtonTapsPublisher = PassthroughSubject&lt;Int, Never&gt;()<br>    <br>    callingButtonTapsPublisher<br>        .prefix(untilOutputFrom: isReceiverReadyPublisher)<br>        .sink { completion in<br>            print(&quot;Received Completion : \(completion)&quot;)<br>        } receiveValue: { value in<br>            print(&quot;Received value : \(value)&quot;)<br>        }<br>        .store(in: &amp;subscriptions)<br>    <br>    (1...6).forEach { currentTap in<br>        callingButtonTapsPublisher.send(currentTap)<br>        <br>        if currentTap == 3 {<br>            isReceiverReadyPublisher.send()<br>        }<br>    }<br>    callingButtonTapsPublisher.send(completion: .finished)<br>}</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TurHdprjHtEAMQWk35HrgA.png" /></figure><blockquote>There are some variants (e.g. same operator with different type of arguments / condition) of all above mentioned Operators, but b<strong>asic working remains the same as explained above</strong>. Feel free to try available variants of the same Operators to boost your confidence.</blockquote><p>In this article, We have explored <strong><em>Filtering Operators</em></strong> of combine. We will deep dive into another exciting type of the Operators : <strong><em>Transforming Operators</em></strong>. Stay tuned with the combine <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><p>Feel free to <a href="https://nikunj-joshi.medium.com/"><strong>follow me</strong></a> to stay updated with the upcoming articles.</p><p>Thank You. Cheers!</p><p><strong>#Pre-Requisite<br></strong><em>Intermediate level of the swift language / iOS is required for this Combine Article series.</em></p><p><strong>#Credits</strong></p><p><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=510d962b95f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Combine — Type Erasure : Abstract Publisher Details]]></title>
            <link>https://nikunj-joshi.medium.com/swift-combine-type-erasure-abstract-publisher-details-86311467295f?source=rss-4dd996182143------2</link>
            <guid isPermaLink="false">https://medium.com/p/86311467295f</guid>
            <category><![CDATA[combine-framework]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[N!kunj Joshi]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 17:55:00 GMT</pubDate>
            <atom:updated>2023-01-27T17:55:00.617Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Combine — Type Erasure : Abstract Publisher Details</h3><p>In the previous <a href="https://nikunj-joshi.medium.com/swift-combine-subject-publishers-passthroughsubject-currentvaluesubject-52fe7fbe58b8">article</a>, we have learnt subject publisher along with its types. In this article, we will explore how we can prevent exposure of extra details for any publisher.</p><blockquote><em>If you are directly coming to this article, basic knowledge of subscriber, publisher and subscription is expected. If you wish to revise feel free to revisit the </em><a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0"><em>learning series</em></a><em>.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfclYAjYvIRvDCg9NNzcOQ.jpeg" /></figure><p>By using ‘<strong><em>Type Erasure</em></strong>’ method provided by Combine, we can achieve abstraction of the exact type of the publisher, preventing the exposure of underlying details to subscribers. <em>Let’s understand this via code.</em></p><pre>import Foundation<br>import Combine<br><br>/*<br> <br> This is a Util function for logs.<br> <br> We will use this function to clearly distinguis the examples of variois topics.<br> Function will take a title of the topic and will execute the blocks after printing.<br> */<br>public func myLearningCode(of title: String,<br>                          execute: () -&gt; Void) {<br>    print(&quot;\n ***** Example of:&quot;, title, &quot;***** \n&quot;)<br>    execute()<br>}<br><br>myLearningCode(of: &quot;Type Erasure&quot;) {<br>    <br>    // 1<br>    class Human {<br>        <br>        // 2<br>        let passthroughSubject = PassthroughSubject&lt;String, Never&gt;()<br>        <br>        // 3<br>        let passthroughSubject2 = PassthroughSubject&lt;String, Never&gt;().eraseToAnyPublisher()<br>        <br>    }<br>    <br>    // 4<br>    let humanObject = Human()<br>    <br>    // 5<br>    print(&quot;Without Type Erasure &quot;)<br>    print(&quot;\(type(of: humanObject.passthroughSubject)) \n&quot;)<br>    <br>    // 6<br>    print(&quot;With Erased Type &quot;)<br>    print(type(of: humanObject.passthroughSubject2))<br><br>}</pre><ol><li>Class with a name ‘<em>Human</em>’. We will have two ‘<strong><em>PassthroughSubject</em></strong>’ publisher properties.</li><li>First ‘<strong><em>PassthroughSubject</em></strong>’ object with <strong><em>String</em></strong> type as a output and <strong><em>Never</em></strong> as a failure type.</li><li>Second ‘<strong><em>PassthroughSubject</em></strong>’ object with <strong><em>String</em></strong> type as a output and <strong><em>Never</em></strong> as a failure type.</li><li>Object of our created class.</li><li>Trying to print ‘<strong><em>type</em></strong>’ of the passthroughSubject without erasing its type.</li><li>Trying to print ‘<strong><em>type</em></strong>’ of the passthroughSubject whose type is erased using ‘<strong><em>eraseToAnyPublisher’</em></strong> method.</li></ol><h4>Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTyiydfBfn_j5M7VQf5SlQ.png" /></figure><p><em>Are you thinking that we have already worked with type erased objects during our previous articles journey? Answer is YES!!!. </em>We were saving our subscriptions with ‘<strong><em>AnyCancellable</em></strong>’ type container, which are also type erased objects.</p><p>The ‘<strong><em>AnyPublisher’ </em></strong>is a type — erased structure which conforms to the default ‘<strong><em>Publisher’ </em></strong>protocol. This helps us to hide information about the publisher’s actual type.</p><p>In this article, we have seen how we can erase type of the publisher to the generic type.</p><p>We have explored all essential topics related to Publisher and Subscriber in this learning series. <strong><em>Now we will explore third pillar of the Combine word: ‘</em>Operators’<em> in upcoming articles.</em></strong></p><p>Stay tuned with the combine <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><p>Feel free to <a href="https://nikunj-joshi.medium.com/"><strong>follow me</strong></a> to stay updated with the upcoming articles.</p><p>Thank You. Cheers!</p><p><strong>#Pre-Requisite<br></strong><em>Intermediate level of the swift language / iOS is required for this Combine Article series.</em></p><p><strong>#Credits</strong></p><p><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86311467295f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Combine — Subject Publishers : PassthroughSubject & CurrentValueSubject]]></title>
            <link>https://nikunj-joshi.medium.com/swift-combine-subject-publishers-passthroughsubject-currentvaluesubject-52fe7fbe58b8?source=rss-4dd996182143------2</link>
            <guid isPermaLink="false">https://medium.com/p/52fe7fbe58b8</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[combine-framework]]></category>
            <dc:creator><![CDATA[N!kunj Joshi]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 18:53:45 GMT</pubDate>
            <atom:updated>2023-01-26T18:53:45.719Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Combine — Subject Publishers : PassthroughSubject &amp; CurrentValueSubject</h3><p>In the previous <a href="https://nikunj-joshi.medium.com/swift-combine-future-9db74f2210cf">article</a>, we have learnt about <strong><em>Future</em></strong> publisher and its working. In this article, we will explore ‘<strong><em>Subject</em></strong>’ publisher.</p><blockquote><em>If you are directly coming to this article, basic knowledge of </em><a href="https://medium.com/@nikunj-joshi/swift-combine-create-your-own-subscriber-4dec1644b373"><em>creating a own custom subscriber</em></a><em>. If you wish to revise feel free to revisit the </em><a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0"><em>learning series</em></a><em>.</em></blockquote><p>Till now in this series, we have mostly explored <em>Publishers</em> with <strong><em>finite</em></strong> number events which emits events <strong><em>sequentially</em></strong> and <strong><em>synchronously</em></strong>. <em>What if you want to send an even </em><strong><em>asynchronously and infinitely </em></strong><em>from the Publisher?</em> I think combine has heard your need and provided ‘<strong><em>Subject</em></strong>’ publishers for the same purpose.</p><p>Do you remember our <a href="https://nikunj-joshi.medium.com/swift-combine-subscription-example-7259204ae8ea">subscription example</a> using NotificationCenter? Notificationcenter was sending events as per its wish <strong><em>asynchronously</em></strong>. We can achieve same using ‘<strong><em>Subject’</em></strong> publishers and emit events to subscriber/s as per wish and need basis.</p><p>Combine ‘<strong><em>Subject’ </em></strong>publishers has two variants for the same purpose of sending events asynchronously according to need base, namely ‘<strong><em>PassthroughSubject’ </em></strong><em>and</em><strong><em> ‘CurrentValueSubject’. </em></strong><em>L</em>et’s explore each in details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*_Ar48Dn0Z_smDtEI8zxJ-A.png" /></figure><h3>PassthroughSubject</h3><p><em>PassthroughSubject</em> as name suggests, this publisher passes through the value to the subscriber/s on demand. We can call ‘<strong><em>send</em></strong>’ method of this publisher to emit an event or completion. This is very helpful when we want to manually emit an event from the Publisher. This seems like our regular coding practice where we send objects / value manually, right? You got it right, ‘<strong><em>Subject</em></strong>’ publishers help us to bridge normal <em>i</em><a href="https://www.geeksforgeeks.org/difference-between-imperative-and-declarative-programming/"><em>mperative code</em></a> with Combine World.</p><p><em>Let’s check how exactly ‘</em><strong><em>PassthroughSubject</em></strong><em>’ works with some coding magic.</em></p><pre>import Foundation<br>import Combine<br><br>/*<br> <br> This is a Util function for logs.<br> <br> We will use this function to clearly distinguis the examples of variois topics.<br> Function will take a title of the topic and will execute the blocks after printing.<br> */<br>public func myLearningCode(of title: String,<br>                          execute: () -&gt; Void) {<br>    print(&quot;\n ***** Example of:&quot;, title, &quot;***** \n&quot;)<br>    execute()<br>}<br><br>myLearningCode(of: &quot;PassthroughSubject&quot;) {<br>    <br>    enum StringError: Error {<br>        case customError<br>    }<br>    <br>    class StringSubscriber: Subscriber {<br>        <br>        typealias Input = String<br>        <br>        typealias Failure = StringError<br>        <br>        func receive(subscription: Subscription) {<br>            subscription.request(.max(3))<br>        }<br>        <br>        func receive(_ input: String) -&gt; Subscribers.Demand {<br>            <br>            switch input.lowercased() {<br>            case &quot;adjust&quot;:<br>                print(&quot;Custom Subscriber: received \(input)&quot;)<br>                print(&quot;Increasing demand to current +1 \n&quot;)<br>                return .max(1)<br>            default:<br>                print(&quot;Custom Subscriber:  received \(input) \n&quot;)<br>                return .none<br>            }<br>        }<br>        <br>        func receive(completion: Subscribers.Completion&lt;StringError&gt;) {<br>            print(&quot;Custom Subscriber: received a completion \(completion) \n&quot;)<br>        }<br>    }<br>}</pre><p><em>We have created a custom subscriber with </em><strong><em>Input</em></strong><em> of </em><strong><em>String</em></strong><em> type and </em><strong><em>error</em></strong><em> of </em><strong><em>user defined StringError enum type</em></strong><em>. If you are struggling to understand this code, please take a pause, revisit our </em><a href="https://medium.com/@nikunj-joshi/swift-combine-create-your-own-subscriber-4dec1644b373"><strong><em>create a custom subscriber</em></strong></a><em> article.</em></p><p><em>Note that, whenever this custom subscriber is receiving a event with value ‘</em><strong><em>adjust</em></strong><em>’, it is increasing its demand to the publisher by +1. This will add 1 to the current demand.</em></p><p>Let’s add some code for ‘<strong><em>PassthroughSubject’ </em></strong>and see how it works.</p><pre>/// ... continue in previous function code<br><br>myLearningCode(of: &quot;PassthroughSubject&quot;) {<br>    <br>    enum StringError: Error {<br>        case customError<br>    }<br>    <br>    class StringSubscriber: Subscriber {<br>        <br>        typealias Input = String<br>        <br>        typealias Failure = StringError<br>        <br>        func receive(subscription: Subscription) {<br>            subscription.request(.max(3))<br>        }<br>        <br>        func receive(_ input: String) -&gt; Subscribers.Demand {<br>            <br>            switch input.lowercased() {<br>            case &quot;adjust&quot;:<br>                print(&quot;Custom Subscriber: received \(input)&quot;)<br>                print(&quot;Increasing demand to current +1 \n&quot;)<br>                return .max(1)<br>            default:<br>                print(&quot;Custom Subscriber:  received \(input) \n&quot;)<br>                return .none<br>            }<br>        }<br>        <br>        func receive(completion: Subscribers.Completion&lt;StringError&gt;) {<br>            print(&quot;Custom Subscriber: received a completion \(completion) \n&quot;)<br>        }<br>    }<br>    <br>    // 1    <br>    let passthroughSubject = PassthroughSubject&lt;String, StringError&gt;()<br><br>    let customSubscriber = StringSubscriber()<br>    <br>    // 2<br>    passthroughSubject.subscribe(customSubscriber)<br>    <br>    // 3<br>    let subscription = passthroughSubject.sink { completion in<br>        print(&quot;Sink :Received a \(completion) \n&quot;)<br>    } receiveValue: { receivedValue in<br>        print(&quot;Sink : \(receivedValue) \n&quot;)<br>    }<br><br>    // 4<br>    passthroughSubject.send(&quot;event1&quot;)<br><br>    // 5<br>    passthroughSubject.send(&quot;more&quot;)<br><br>    // 6<br>    passthroughSubject.send(&quot;event3&quot;)<br>    passthroughSubject.send(&quot;event4&quot;)<br><br>    // 7<br>    passthroughSubject.send(&quot;event5&quot;)<br>    <br>}</pre><ol><li>Created a ‘<strong><em>PassthroughSubject</em></strong>’ publisher object with an output of a ‘<strong><em>String’</em></strong> type and error of a ‘<strong><em>StringError</em></strong>’ type. Here, ‘<strong><em>StringError’</em></strong> is a <em>user defined enum from the Error protocol</em>.</li><li>Custom subscriber object is subscribed with <strong><em>passthroughSubject</em></strong><em>. </em>This will create a subscription.</li><li>Created another subscription using ‘<strong><em>sink</em></strong>’ and saved as a ‘<strong><em>subscription</em></strong><em>’ </em>property<em>.</em></li><li>Sent an event using <strong><em>passthroughSubject</em></strong><em> with the value ‘</em><strong>event1</strong>’.</li><li>Sent an event using <strong><em>passthroughSubject</em></strong><em> with value ‘</em><strong>more</strong>’. This will inforce subscriber to increase its demand as per our implementation in custom subscriber class.</li><li>Sent couple more events using our passthrough publisher.</li><li>Sent an event using <strong><em>passthroughSubject</em></strong><em> with the value ‘</em><strong>event5</strong>’.</li></ol><h4>Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzEs-VaUZZp3BtCcvc8PZg.png" /></figure><p>If you notice, ‘<strong><em>event5</em></strong>’ is not received by our ‘<strong><em>customSubscriber</em></strong>’, WHY??!!!<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -<br>It’s time to think the answer of above question………………………<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -<br><em>Reason is, </em><strong><em>customSubscriber</em></strong><em> has initially asked for the 3 events at </em><strong><em>‘subscription.request(.max(3))’, </em></strong><em>on receiving ‘</em><strong><em>adjust</em></strong><em>’ input for the second event, publisher was told to adjust demand by +1, so new max events allowed to receive by this subscriber become 3 + 1 = 4. Now, when publisher is sending its </em><strong><em>fifth event</em></strong><em>, </em><strong><em>custom subscriber is not going to entertain it</em></strong><em>.</em> I hope you also thought same before reading this answer, if not, please give <em>our </em><a href="https://medium.com/@nikunj-joshi/swift-combine-create-your-own-subscriber-4dec1644b373"><strong><em>create a custom subscriber</em></strong></a><em> article a try, again.</em></p><p>Let’s try to send some more events and see the behaviour.</p><pre>// 8    <br>subscription.cancel()<br><br>passthroughSubject.send(&quot;event6&quot;)<br><br>// 9<br>passthroughSubject.send(completion: .finished)<br><br>// 10<br>passthroughSubject.send(completion: .failure(.customError))</pre><p>8. This will cancel the subscription we have created using ‘<strong><em>sink</em></strong>’.</p><p>9. Emitted a completion event with ‘<strong><em>finished</em></strong><em>’</em>.</p><p>10. Emitted a completion with our <strong><em>customError</em></strong> as a failure value.</p><h4>Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0ilK5YWyRsJFPWF_-d9bA.png" /></figure><p><em>Some points to infer from this output:</em></p><p><em>‘</em><strong>event6</strong><em>’ : Not received by custom subscriber as its max allowed event count is over. Not received by sink subscriber because it is already cancelled before this event.</em></p><p><strong>completion with ‘finished’ </strong>:<em> Received by custom subscriber although its max allowed event count is over.</em></p><p><strong>completion with ‘failure’ : </strong><em>Not received by both subscriber as one is already cancelled and another has already received a completion before this.</em></p><h3>CurrentValueSubject</h3><p><strong><em>CurrentValueSubject </em></strong><em>publisher</em><strong><em> </em></strong><em>works exactly same as </em><strong><em>PassthroughSubject</em></strong> <em>with some as additional capabilities.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gk19DZuTPSf-5m_R8dSv7Q.png" /></figure><ol><li><strong><em>CurrentValueSubject </em></strong><em>takes initial value at initialization and emits it as soon as any subscriber subscribes with it.</em></li><li><strong><em>‘value</em></strong>’ property can be set manually using assignment operator (=). Change in <strong><em>value</em></strong> property will create an emission to all subscriber automatically.</li><li><strong><em>CurrentValueSubject </em></strong><em>gives us facility to check current value (last emitted event value or initial event value) via its ‘</em><strong><em>value</em></strong>’ property.</li><li>Completion event can’t be assigned directly to the <strong><em>‘value</em></strong>’ property of the <em>CurrentValueSubject </em>subscriber<em>.</em></li></ol><p>Let’s copy above code of ‘<em>PassthroughSubject</em><strong><em>’ </em></strong><em>and validate above points.</em></p><pre>import Foundation<br>import Combine<br><br>/*<br> <br> This is a Util function for logs.<br> <br> We will use this function to clearly distinguis the examples of variois topics.<br> Function will take a title of the topic and will execute the blocks after printing.<br> */<br>public func myLearningCode(of title: String,<br>                          execute: () -&gt; Void) {<br>    print(&quot;\n ***** Example of:&quot;, title, &quot;***** \n&quot;)<br>    execute()<br>}<br><br>myLearningCode(of: &quot;CurrentValueSubject&quot;) {<br>    <br>    enum StringError: Error {<br>        case customError<br>    }<br>    <br>    class StringSubscriber: Subscriber {<br>        <br>        typealias Input = String<br>        <br>        typealias Failure = StringError<br>        <br>        func receive(subscription: Subscription) {<br>            subscription.request(.max(3))<br>        }<br>        <br>        func receive(_ input: String) -&gt; Subscribers.Demand {<br>            <br>            switch input.lowercased() {<br>            case &quot;adjust&quot;:<br>                print(&quot;Custom Subscriber: received \(input)&quot;)<br>                print(&quot;Increasing demand to current +1 \n&quot;)<br>                return .max(1)<br>            default:<br>                print(&quot;Custom Subscriber:  received \(input) \n&quot;)<br>                return .none<br>            }<br>        }<br>        <br>        func receive(completion: Subscribers.Completion&lt;StringError&gt;) {<br>            print(&quot;Custom Subscriber: received a completion \(completion) \n&quot;)<br>        }<br>    }<br>    <br>    // 1.<br>    let currentValueSubject = CurrentValueSubject&lt;String, StringError&gt;(&quot;Initial Value&quot;)<br>    <br>    let customSubscriber = StringSubscriber()<br>    <br>    currentValueSubject.subscribe(customSubscriber)<br>    <br>    _ = currentValueSubject.sink { completion in<br>        print(&quot;Sink :Received a \(completion) \n&quot;)<br>    } receiveValue: { receivedValue in<br>        print(&quot;Sink : \(receivedValue) \n&quot;)<br>    }<br>}</pre><h4>Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kl7FweL6ZCAWClRhe3ZJRA.png" /></figure><p><em>We haven’t published any event manually from our currentValueSubject, although both of our subscription have received an event with initially assigned value of ‘</em><strong><em>CurrentValueSubject’.</em></strong></p><p>Let’s emit some events manually from our publisher.</p><pre>myLearningCode(of: &quot;CurrentValueSubject&quot;) {<br>    <br>    enum StringError: Error {<br>        case customError<br>    }<br>    <br>    class StringSubscriber: Subscriber {<br>        <br>        typealias Input = String<br>        <br>        typealias Failure = StringError<br>        <br>        func receive(subscription: Subscription) {<br>            subscription.request(.max(3))<br>        }<br>        <br>        func receive(_ input: String) -&gt; Subscribers.Demand {<br>            <br>            switch input.lowercased() {<br>            case &quot;adjust&quot;:<br>                print(&quot;Custom Subscriber: received \(input)&quot;)<br>                print(&quot;Increasing demand to current +1 \n&quot;)<br>                return .max(1)<br>            default:<br>                print(&quot;Custom Subscriber:  received \(input) \n&quot;)<br>                return .none<br>            }<br>        }<br>        <br>        func receive(completion: Subscribers.Completion&lt;StringError&gt;) {<br>            print(&quot;Custom Subscriber: received a completion \(completion) \n&quot;)<br>        }<br>    }<br>    <br>    // 1.<br>    let currentValueSubject = CurrentValueSubject&lt;String, StringError&gt;(&quot;Initial Value&quot;)<br>    <br>    let customSubscriber = StringSubscriber()<br>    <br>    currentValueSubject.subscribe(customSubscriber)<br>    <br>    _ = currentValueSubject.sink { completion in<br>        print(&quot;Sink :Received a \(completion) \n&quot;)<br>    } receiveValue: { receivedValue in<br>        print(&quot;Sink : \(receivedValue) \n&quot;)<br>    }<br><br>    // 2<br>    currentValueSubject.value = &quot;updated value property using = operator&quot;<br>    <br>    currentValueSubject.send(&quot;event1&quot;)<br>    <br>    // 3<br>    print(&quot;currentValueSubject.value is: \(currentValueSubject.value)&quot;)<br>  <br>    // 4<br>    /// currentValueSubject.value = .finished<br>}</pre><h4>Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BpBSKhEPZr4Fy8zgX9N_qg.png" /></figure><p><em>Above output is totally aligned with all four points discussed above for the ‘</em><strong><em>CurrentValueSubject’.</em></strong></p><h4>Summary</h4><ul><li><em>‘</em><strong><em>PassthroughSubject</em></strong><em>’ and ‘</em><strong><em>CurrentValueSubject’ </em></strong><em>give us luxury to emit event/s on demand or as per need basis asynchronously and infinitely.</em></li><li><em>‘</em><strong><em>CurrentValueSubject’ </em></strong>gives some extra capability of giving a publisher an initial value as well as emitting an event automatically by updating its ‘<strong><em>value’</em></strong> property.</li></ul><p>We have learnt about <strong><em>Subject</em></strong> publisher and its types. We are about to become a ‘<em>ninja</em>’ of <em>Subscriber and Publisher topics</em> once we complete ‘<strong><em>Type Erasure’ </em></strong>in next article. Stay tuned with the combine <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><p>Feel free to <a href="https://nikunj-joshi.medium.com/"><strong>follow me</strong></a> to stay updated with the upcoming articles.</p><p>Thank You. Cheers!</p><p><strong>#Pre-Requisite<br></strong><em>Intermediate level of the swift language / iOS is required for this Combine Article series.</em></p><p><strong>#Credits</strong></p><p><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52fe7fbe58b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Combine — Future]]></title>
            <link>https://nikunj-joshi.medium.com/swift-combine-future-9db74f2210cf?source=rss-4dd996182143------2</link>
            <guid isPermaLink="false">https://medium.com/p/9db74f2210cf</guid>
            <category><![CDATA[combine-framework]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[N!kunj Joshi]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 09:34:48 GMT</pubDate>
            <atom:updated>2023-01-26T19:59:35.659Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Combine — Future Publisher</h3><p>In the previous <a href="https://nikunj-joshi.medium.com/swift-combine-create-your-own-subscriber-4dec1644b373">article</a>, we have explored on how to create our custom subscriber according to our use case need. In this article, we will explore ‘<strong><em>Future</em></strong>’ publisher.</p><blockquote>If you are directly coming to this article, basic knowledge of subscriber, publisher and subscription is expected. If you wish to revise feel free to revisit the <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</blockquote><p>Do you remember the <a href="https://nikunj-joshi.medium.com/swift-combine-just-publisher-51e7f9051438">‘Just’ Publisher</a>? <em>‘</em><strong><em>Just</em></strong><em>’ publisher was publishing a single event immediately and completing itself</em>. <strong><em>What if we want to do the same thing of sending an event but in the future time after completing some other work? </em></strong><em>‘</em><strong><em>Future</em></strong><em>’ </em>publisher exactly does the same. It allows to emit an event at some point of time in future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*tJM_S7d1QxRLZpEs_QAkug.png" /></figure><p>We can create a <strong><em>Future</em></strong> publisher with its expected output type and error. Once asynchronous task is complete, we can emit its result as an event from the created <strong><em>Future</em></strong>. Emitting the event is done via <em>Promise. </em>Let’s check default implementation of the <strong><em>Future </em></strong>publisher from the combine framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R30SVx35oPm6JST-rH9w4w.png" /></figure><p><strong><em>Future </em></strong><em>publisher will allow us to emit an event in future time via Promise. </em><strong><em>Promise</em></strong> is just a closure. It is a escaping closure which gets called when <em>Future</em> publisher is ready to emit an event.</p><p>Assume, you want to show ‘<em>current quote of the day’</em> on various screens of the app, you will have an network API call and will display quote once API response is successful. This situation best fits with the use of <strong><em>Future</em></strong> publisher. Let’s experiment with some code.</p><pre>import Foundation<br>import Combine<br><br>/*<br> This is a Util function for logs.<br> Function will take a title of the topic and will execute the blocks<br> after printing.<br> */<br><br>public func myLearningCode(of title: String,<br>                           execute: () -&gt; Void) {<br>    print(&quot;\n ***** Example of:&quot;, title, &quot;***** \n&quot;)<br>    execute()<br>}<br><br>myLearningCode(of: &quot;Future Publisher&quot;) {<br>    <br>    // 1<br>    let fetchQuoteFuture: Future&lt;String, Never&gt; = {<br>        <br>        // 2<br>        return Future&lt;String, Never&gt; { promise in<br>            <br>            // 3 <br>            DispatchQueue.global().asyncAfter(deadline: .now() + 3.0) {<br>                <br>                // 4<br>                promise(.success(&quot;Future is here, Where are you?!!&quot;))<br>                <br>            }<br>        }<br>        <br>    }()<br>}</pre><ol><li>Created a <strong><em>Future</em></strong> with a value of <em>String</em> and error as <em>Never</em> type. ‘fetchQuoteFuture’ property saves the returned <strong><em>Future</em></strong> publisher object from the followed function block.</li><li><strong><em>Future</em></strong> publisher closure which gives access to the <em>promise</em> to emit an event at later stage. We will use this <em>promise</em> to emit an event once asynchronous work is done and publisher is ready to transmit an even to the subscriber.</li><li>Using global DispatchQueue with asyncAfter to simulate the actual API call.</li><li><em>promise</em> returns the success with the output value of the <strong><em>Future</em></strong>.</li></ol><p><em>Add some more code to continue our example.</em></p><pre>myLearningCode(of: &quot;Future Publisher&quot;) {<br>    <br>    /// .... continue from previous code<br><br>// 5<br>var subscriptions = Set&lt;AnyCancellable&gt;()<br><br>// 6<br>fetchQuoteFuture.sink { completion in<br>        <br>        print(&quot;1. \(completion) \n&quot;)<br>    <br>    } receiveValue: { receivedValue in<br>    <br>        print(&quot;1. A value &#39; \(receivedValue) &#39; from the Future Publisher \n&quot;)<br>    <br>    }<br>    .store(in: &amp;subscriptions)<br><br>// 7<br>fetchQuoteFuture.sink { completion in<br>    <br>        print(&quot;2. \(completion) \n&quot;)<br>    <br>    } receiveValue: { receivedValue in<br>    <br>        print(&quot;2. A value &#39; \(receivedValue) &#39; from the Future Publisher \n&quot;)<br>    <br>    }<br>    .store(in: &amp;subscriptions)<br>}</pre><p>5. We are using a Set with AnyCancellable element type, this will help us to store all our subscription at one place with an organised manner.</p><p>6. Created a subscription with <em>sink </em>subscriber. <strong>‘.store(in: &amp;subscriptions)’ </strong>helps to store created subscription into subscriptions set. Storing subscription into a set helps us to cancel all the subscription at once using this container.</p><p>7. Created another subscription with <em>sink </em>subscriber same as step #6.</p><p><em>Rub above code and see the output.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Wj4Kw9uueddLT4v4d_r-g.png" /></figure><p><strong><em>Ohh.!! None of our subscriptions are getting event from the publisher!.</em></strong> Reason is, <em>if you see our container which stores the subscriptions, is limited to scope of our function only. Remember, we have learnt that combine provides us automatic memory management. Subscription gets deinitialized once its holding or container object gets deinitialized. That is exactly what is happening here, before </em><strong><em>Future</em></strong><em> return its promise after 3.0 seconds, ‘</em>subscriptions<em>’ container is getting deinitialized with the function scope, which is cancelling our both subscriptions.</em></p><p>Try to move subscription container (<em>step #5</em>) out of the function scope and run the code.</p><pre>// 5<br>var subscriptions = Set&lt;AnyCancellable&gt;()<br><br>myLearningCode(of: &quot;Future Publisher&quot;) {<br>    <br>/// .... moving step #5 out of function scope<br><br>// 6<br>fetchQuoteFuture.sink { completion in<br>        <br>        print(&quot;1. \(completion) \n&quot;)<br>    <br>    } receiveValue: { receivedValue in<br>    <br>        print(&quot;1. A value &#39; \(receivedValue) &#39; from the Future Publisher \n&quot;)<br>    <br>    }<br>    .store(in: &amp;subscriptions)<br><br>// 7<br>fetchQuoteFuture.sink { completion in<br>    <br>        print(&quot;2. \(completion) \n&quot;)<br>    <br>    } receiveValue: { receivedValue in<br>    <br>        print(&quot;2. A value &#39; \(receivedValue) &#39; from the Future Publisher \n&quot;)<br>    <br>    }<br>    .store(in: &amp;subscriptions)<br>}</pre><h4>Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lt3p-qyjZqoHHGmLVPcZQ.png" /></figure><p>or</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uu104Idf9obEobdqf2zmSA.png" /></figure><p><em>We have two subscription for our future publisher which sends asynchronous event, so order of receiving value from the Future publisher may varies.</em></p><p>We have learnt how we can use <strong><em>Future</em></strong> publisher to transmit an event at later stage asynchronously<strong>. </strong><em>This gives publisher a luxury to complete any long running asynchronous task without blocking the calling thread and emit an event once it has some output value for its subscribers. </em><br>We will give a try to understand <strong>‘<em>Subject</em>’ </strong>publisher<strong> </strong>in our next article. Stay tuned with the combine <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><p>Feel free to <a href="https://nikunj-joshi.medium.com/"><strong>follow me</strong></a> to stay updated with the upcoming articles.</p><p>Thank You. Cheers!</p><p><strong>#Pre-Requisite<br></strong><em>Intermediate level of the swift language / iOS is required for this Combine Article series.</em></p><p><strong>#Credits</strong></p><p><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9db74f2210cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Combine —Create Your Own Subscriber]]></title>
            <link>https://nikunj-joshi.medium.com/swift-combine-create-your-own-subscriber-4dec1644b373?source=rss-4dd996182143------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dec1644b373</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[combine-framework]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[N!kunj Joshi]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 10:55:04 GMT</pubDate>
            <atom:updated>2023-01-26T07:18:50.286Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Combine —Create Your Own Custom Subscriber</h3><p>In the previous <a href="https://nikunj-joshi.medium.com/swift-combine-deep-dive-into-publisher-subscriber-and-subscription-protocols-bbde0e61de8f">article</a>, we have learnt about default protocols of ‘<em>Publisher</em>’, ‘<em>Subscriber</em>’ and ‘<em>Subscription</em>’. Many times we need our custom subscriber according to our use case need. In this article, we will explore how we can create our own subscriber by adopting the default ‘<strong><em>Subscriber</em></strong>’ protocol.</p><blockquote><em>If you are directly coming to this article, basic knowledge of subscriber, publisher and subscription is expected. If you wish to revise feel free to revisit the </em><a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0"><em>learning series</em></a><em>.</em></blockquote><p>Let’s say we want to create our own OrderNumber subscriber which monitors the emitted order number according to our use case. Let’s jump on the xcode playground and add below code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*rp1ks1Sx2x9BgEBj1bYKow.png" /></figure><p>Remember, we are going to see practical coding of all steps from our subscription diagram of our <a href="https://nikunj-joshi.medium.com/swift-combine-deep-dive-into-publisher-subscriber-and-subscription-protocols-bbde0e61de8f">previous article</a>. Let’s reload it into our mind memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*i5csTPIds9_Tzth61XTQAg.png" /></figure><p>Create a ‘OrderNumberSubscriber’ subscriber class which conforms to ‘<strong><em>Subscriber</em></strong>’ protocol. Add all required methods of that protocol. Xcode will ask you to define <strong><em>Input</em></strong> and <strong><em>Failure</em></strong> type, we will add <strong><em>Int</em></strong> for <strong><em>Input</em></strong> and <strong><em>Never</em></strong> for failure. We can make this class ‘<strong>final</strong>’, if we want to prevent inheritance from this subscriber.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r6Er0aAqgbVoL5uATyf8Fg.png" /></figure><h3>Subscribers.Demand</h3><p>When subscriber receives value from the Publisher in <strong><em>func receive(_ input: Int) -&gt; Subscribers.Demand </em></strong>method, it asks for the future need of elements as a Demand. <br>On the receiving each value, Subscriber can decide and adjust its demand for the future event. Managing and Adjusting demand dynamically is known as ‘<strong>Backpressure Management</strong>’. <strong><em>This helps a subscriber to not get over flooded with the values from the publisher more than it can handle or wanted.</em></strong></p><p>Widely used ‘<strong><em>Subscribers.Demand</em></strong>’ are:</p><ul><li><strong>unlimited : </strong><em>This demand informs publisher that Subscriber is still ready to handle unlimited events.</em></li><li><strong>none : </strong><em>This demand informs publisher that Subscriber is not interested to adjust its demand. Just stick with its original asked demand of the events.</em></li><li><strong>max(value: Int)</strong> : <em>This informs publisher to adjust previously asked demand with new value.</em> Value passed in demand<strong> must be positive</strong> to avoid fatal error. Once subscriber adjust its demand, <em>new demand will be increased from the previously asked demand.</em> <strong><em>This implies that you can raise the initial max with each new value received, however, it cannot be lowered.</em></strong></li></ul><p>Let’s continue our coding example and add some code.</p><pre><br>import Foundation<br>import Combine<br><br>/*<br> This is a Util function for logs.<br> Function will take a title of the topic and will execute the blocks<br> after printing.<br> */<br><br>public func myLearningCode(of title: String,<br>                           execute: () -&gt; Void) {<br>    print(&quot;\n ***** Example of:&quot;, title, &quot;***** \n&quot;)<br>    execute()<br>}<br><br>// 1<br>myLearningCode(of: &quot;Custom Subscriber&quot;) {<br>    <br>    // 2<br>    class OrderNumberSubscriber: Subscriber {<br>        <br>        // 3<br>        typealias Input = Int<br>        <br>        // 4<br>        typealias Failure = Never<br>        <br>        // 5<br>        func receive(subscription: Subscription) {<br>            subscription.request(.max(5))<br>        }<br>        <br>        // 6<br>        func receive(_ input: Int) -&gt; Subscribers.Demand {<br>            print(&quot;received a value \(input)&quot;)<br>            return .none<br>        }<br>        <br>        // 7<br>        func receive(completion: Subscribers.Completion&lt;Never&gt;) {<br>            print(&quot;received a completion \(completion)&quot;)<br>        }<br>    }<br>}</pre><ol><li>Our helper function to log example title into console.</li><li>Created a class ‘<em>OrderNumberSubscriber</em>’ which conforms the default ‘<em>Subscriber</em>’ protocol.</li><li>Defined Input type our custom subscriber is willing to receive.</li><li>Defined Failure type for our custom subscriber. User ‘Never’ which suggest subscriber won’t receive any error.</li><li>This is a callback from the Publisher with the created subscription instance. Subscriber asks for the initial demand via ‘<em>request</em>’ method. <strong><em>Map this with step #2 from the Publisher side and step #3 from the subscriber side of our above mentioned communication sequence diagram.</em></strong></li><li>Gets called every time publisher emits the event. Our subscriber will get those events in this callback. Subscriber can adjust future demand according to need.</li><li>Defines the completion callback from the Publisher.</li></ol><p>Next step is to create a Publisher for it. We will use simple Integer range pubshiber for this example.</p><pre>// 1<br>myLearningCode(of: &quot;Custom Subscriber&quot;) {<br>    <br>    // 2<br>    class OrderNumberSubscriber: Subscriber {<br>        <br>        // 3<br>        typealias Input = Int<br>        <br>        // 4<br>        typealias Failure = Never<br>        <br>        // 5<br>        func receive(subscription: Subscription) {<br>            subscription.request(.max(5))<br>        }<br>        <br>        // 6<br>        func receive(_ input: Int) -&gt; Subscribers.Demand {<br>            print(&quot;received a value \(input)&quot;)<br>            return .none<br>        }<br>        <br>        // 7<br>        func receive(completion: Subscribers.Completion&lt;Never&gt;) {<br>            print(&quot;received a completion \(completion)&quot;)<br>        }<br>    }<br><br>    // 8<br>    let orderPublisher = (1...10).publisher<br><br>    // 9<br>    let orderSubscriber = OrderNumberSubscriber()<br><br>    // 10<br>    orderPublisher.subscribe(orderSubscriber)<br>}</pre><p>Let’s run and see the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RLhvoEtk52HK6rSHooNncQ.png" /></figure><p>Wait..!! Why we haven’t received a completion call from the Publisher? !!! <br>Because, we have demanded max(5) events in our step #5 while creating the initial demand, but Publisher do have more events.</p><p>Let’s try to adjust our demand to <strong><em>unlimited</em></strong> (<em>step #6</em>)on receiving each value and see.</p><pre>// 1<br>myLearningCode(of: &quot;Custom Subscriber&quot;) {<br>    <br>    // 2<br>    class OrderNumberSubscriber: Subscriber {<br>        <br>        // 3<br>        typealias Input = Int<br>        <br>        // 4<br>        typealias Failure = Never<br>        <br>        // 5<br>        func receive(subscription: Subscription) {<br>            subscription.request(.max(5))<br>        }<br>        <br>        // 6<br>        func receive(_ input: Int) -&gt; Subscribers.Demand {<br>            print(&quot;received a value \(input)&quot;)<br>            // 11<br>            return .unlimited<br>        }<br>        <br>        // 7<br>        func receive(completion: Subscribers.Completion&lt;Never&gt;) {<br>            print(&quot;received a completion \(completion)&quot;)<br>        }<br>    }<br><br>    // 8<br>    let orderPublisher = (1...10).publisher<br><br>    // 9<br>    let orderSubscriber = OrderNumberSubscriber()<br><br>    // 10<br>    orderPublisher.subscribe(orderSubscriber)<br>}</pre><p>11. On receiving the event, subscriber will still get chance to adjust its initial events demand from the Publisher for the future events. <em>We are using unlimited demand which is telling publisher to send as much as possible events after the current received one.</em></p><p>Run the code and you must receive now completion event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmVCOJwXz2xwxmVLpU926A.png" /></figure><p>Try changing ‘<strong>.unlimited’ </strong>demand to <strong>‘.max(2)’ at step #11</strong>, you will see same output because <strong>subscriber is increasing its demand by 2 every time it is receiving the value.</strong> <br><em>Try playing around this demand change and see the difference in output to understand this in depth. Also, try to comment ‘</em><strong><em>subscription.request(.max(5))</em></strong><em>’ line (</em><strong><em>step #5</em></strong><em>) and see what is the output.</em></p><p>We have understood the creation and working of a <strong>Custom Subscriber </strong>and its communication callbacks from the Publisher<strong>. </strong>We will head towards exploring <strong>‘<em>Future</em>’</strong> in our next article. Stay tuned with the combine <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><p>Feel free to <a href="https://nikunj-joshi.medium.com/"><strong>follow me</strong></a> to stay updated with the upcoming articles.</p><p>Thank You. Cheers!</p><p><strong>#Pre-Requisite<br></strong><em>Intermediate level of the swift language / iOS is required for this Combine Article series.</em></p><p><strong>#Credits</strong></p><p><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dec1644b373" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Combine — Deep Dive into Publisher, Subscriber and Subscription Protocols]]></title>
            <link>https://nikunj-joshi.medium.com/swift-combine-deep-dive-into-publisher-subscriber-and-subscription-protocols-bbde0e61de8f?source=rss-4dd996182143------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbde0e61de8f</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[combine-framework]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[N!kunj Joshi]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 16:18:42 GMT</pubDate>
            <atom:updated>2023-01-24T06:40:22.161Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Combine — Deep Dive into Publisher, Subscriber and Subscription Protocols</h3><p>In the previous <a href="https://nikunj-joshi.medium.com/swift-combine-assign-subscriber-358e4fe25303">article</a>, we have learnt about ‘<strong><em>Assign</em></strong>’ subscriber. We will understand default protocols of ‘<em>Publisher</em>’, ‘<em>Subscriber</em>’ and ‘<em>Subscription</em>’ in this article so you will have understanding of internal workings of these.</p><blockquote><em>If you are directly coming to this article, basic knowledge of subscriber, publisher and subscription is expected.</em> If you wish to revise feel free to revisit the <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</blockquote><p>In our article about <a href="https://medium.com/@nikunj-joshi/swift-combine-basics-572752734d2c">combine basics</a>, we have learnt that, to create a subscription, both Publisher and Subscriber play significant role. An image paints a thousand words, so to start off, let’s use one to demonstrate the internal working between publishers and subscribers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*i5csTPIds9_Tzth61XTQAg.png" /></figure><p>Image itself is a self explanatory. All 5 steps plays crucial role during any subscription. Let’s try to break out all those steps and understand via actual protocols of each from the Combine framework.</p><h3>Publisher Protocol</h3><p>Try to write ‘<strong><em>Publisher</em></strong>’ in a xcode playground and see its implementation (<em>press Command + Control keys</em>), which says ‘<strong><em>It is a type that transmits sequence of events over time</em></strong>’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*EkyT3UMqWmyI6nn-AQZiqQ.png" /></figure><p>Let’s try to understand ‘<strong><em>Publisher</em></strong>’ protocol.</p><pre>// 1<br>public protocol Publisher {<br><br>    // 2<br>    associatedtype Output<br><br>    // 3<br>    associatedtype Failure : Error<br><br>    // 4<br>    func receive&lt;S&gt;(subscriber: S) where S : Subscriber,<br>                                         Self.Failure == S.Failure,<br>                                         Self.Output == S.Input<br>}<br><br>extension Publisher {<br><br>    // 5<br>    public func subscribe&lt;S&gt;(_ subscriber: S) where S : Subscriber,<br>                                                    Self.Failure == S.Failure,<br>                                                    Self.Output == S.Input<br>}</pre><ol><li>Default ‘<em>Publisher</em>’ protocol available from the Combine Framework.</li><li><em>The kind of the output values published by this publisher.</em></li><li><em>The kind of errors this publisher might publish.</em><strong><em> Use `Never` if this `Publisher` does not publish errors.</em></strong></li><li><strong><em>Attaches the specified subscriber to this publisher. This is a required method to implement for any Publisher. Where: <br></em></strong><em>Incoming subscriber must be adopting ‘Subscriber’ protocol</em>. <strong><br></strong><em>Publisher’s output type must match with Subscriber’s input type.</em> <br>‘<strong><em>Failure</em></strong><em>’ of subscriber and Publisher must be of same type.</em></li><li>Function ‘<strong>subscribe</strong>’ which takes a subscriber as a parameter with same conditions like step #4 function.<br><strong><em>Always call ‘subscribe’ function to attach any subscriber to the Publisher. This method internally calls ‘receive’ method. </em></strong>(<strong><em>Step #1 in above communication diagram</em></strong>)</li></ol><h3>Subscriber Protocol</h3><p>Try to write ‘<strong><em>Subscriber</em></strong>’ in a xcode playground and see its implementation (<em>press Command + Control keys</em>), which says ‘<strong><em>A protocol that declares a type that can receive input from a publisher.</em></strong>’</p><p>Let’s try to understand ‘<strong>Subscriber</strong>’ protocol.</p><pre>// 1<br>public protocol Subscriber : CustomCombineIdentifierConvertible {<br><br>    // 2<br>    associatedtype Input<br><br>    // 3<br>    associatedtype Failure : Error<br><br>    // 4<br>    func receive(subscription: Subscription)<br><br>    // 5<br>    func receive(_ input: Self.Input) -&gt; Subscribers.Demand<br><br>    // 6<br>    func receive(completion: Subscribers.Completion&lt;Self.Failure&gt;)<br>}</pre><ol><li>Default ‘<strong><em>Subscriber</em></strong>’ protocol available from the Combine Framework.</li><li><em>The kind of values this subscriber receives.</em></li><li><em>The kind of errors this publisher might publish.</em><strong><em> Use `Never` if this `Subscriber` does not receive errors.</em></strong></li><li>Defines that requested subscription is already successful from the Publisher side. Subscriber may request items. (<strong><em>Step #2 in above communication diagram</em></strong>)<br>Subscriber receives instance of the subscription as a parameter of this method.</li><li>Gets called when there is any event received from the Publisher event. This will get called for every emitted events from the Publisher. Subscriber can adjust its demand about future events in return, if it wants. (<em>Will see more about ‘Demand’ in our next custom subscriber article</em>) (<strong><em>Step #4 in above communication diagram</em></strong>)</li><li>Gets called when Publisher sends a completion event either with success or failure. (<strong><em>Step #5 in above communication diagram</em></strong>)</li></ol><h3>Subscription Protocol</h3><p>Try to write ‘<strong><em>Subscription</em></strong>’ in a xcode playground and see its implementation (<em>press Command + Control keys</em>), which says ‘<strong><em>A protocol representing the connection of a subscriber to a publisher</em></strong>.’</p><p>Let’s try to understand ‘<strong><em>Subscription</em></strong>’ protocol.</p><pre>// 1<br>public protocol Subscription : Cancellable,<br>                               CustomCombineIdentifierConvertible {<br><br>    // 2<br>    func request(_ demand: Subscribers.Demand)<br>}</pre><ol><li>Default ‘<strong><em>Subscription</em></strong>’ protocol available from the Combine Framework.</li><li>Calling this method on any subscription instance <strong><em>tells a publisher that it may send more values to the subscriber.<br></em></strong>It takes ‘<strong>Subscribers.Demand</strong>’ as a parameter, which tells Publisher about either more events to publish to the subscriber or not.</li></ol><h3>Cancellable</h3><p>Notice that <em>Subscription</em> protocol confirms to ‘<strong><em>Cancellable</em></strong>’ protocol. When a subscriber completes its task and no longer wishes to receive values from a publisher, <strong><em>canceling the subscription is a recommended practice </em></strong>to release resources and prevent any related activities such as any current / future network calls related to that subscription.</p><p>When any subscription is successful, subscriber of that subscription always receives a unique ‘<strong><em>Cancellation Token</em></strong>’ using which particular subscription can be cancelled any time as per need basis. <strong><em>Cancellation Token </em></strong>defines identity of any Subscription.</p><p>If you don’t explicitly invoke <strong><em>cancel</em></strong> function on a subscription, it will persist until the publisher finishes transmission of the events or until standard memory management causes a stored subscription to be deinitialized.</p><p><strong><em>Make sure cancelling a subscription must be thread-safe.</em></strong></p><h3>Summary</h3><ul><li>Publisher will have one important method to allow subscription from the subscriber.</li><li>Subscriber relies on three methods responsible for receiving a created subscription instance, receiving a values and receiving a completion.</li><li>Subscription can request values using ‘<strong><em>Demand</em></strong>’ to the publisher. Those values will be received by the subscriber.</li><li>Any subscription can be cancelled by calling ‘<strong><em>cancel</em></strong>’ method on it.</li></ul><p>We have understood default protocols of the <strong>Publisher, Subscriber and Subscription</strong>. We will explore creating a ‘<strong><em>Custom Subscriber</em></strong>’ in our next article. Stay tuned with the combine <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><p>Feel free to <a href="https://nikunj-joshi.medium.com/"><strong>follow me</strong></a> to stay updated with the upcoming articles.</p><p>Thank You. Cheers!</p><p><strong>#Pre-Requisite<br></strong><em>Intermediate level of the swift language / iOS is required for this Combine Article series.</em></p><p><strong>#Credits</strong></p><p><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbde0e61de8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Combine — ‘ASSIGN’ Subscriber]]></title>
            <link>https://nikunj-joshi.medium.com/swift-combine-assign-subscriber-358e4fe25303?source=rss-4dd996182143------2</link>
            <guid isPermaLink="false">https://medium.com/p/358e4fe25303</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[combine-framework]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[N!kunj Joshi]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 14:33:25 GMT</pubDate>
            <atom:updated>2023-01-21T14:33:25.432Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Combine — ‘ASSIGN’ Subscriber</h3><p>In the previous <a href="https://medium.com/@nikunj-joshi/swift-combine-just-publisher-51e7f9051438">article</a>, we have learnt about ‘<strong><em>Just</em></strong>’ publisher. This article will focus on ‘<strong>assign</strong>’ subscriber.<em> If you are directly coming to this article, basic knowledge of subscriber, publisher and sink is expected.</em> If you wish to revise feel free to revisit the <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHI1qL1i7Kej-jzniYyhFg.jpeg" /></figure><p>We have seen working of ‘<strong>sink</strong>’ subscriber with its callbacks. Sometimes we simply need to assign received event values to other properties or variables. In this case, we case use ‘<strong>assign</strong>’ subscriber instead of ‘<strong>sink</strong>’.</p><p>“<strong>assign</strong>” subscriber has two variants: <strong>assign(to:on:) </strong>and <strong>assign(to:). </strong>Let’s see working of both and when to use which one.</p><p>‘<strong>assign</strong>’ enables us to assign received values to other <a href="https://medium.com/@abhishek1nacc/kvo-key-value-observing-in-swift-65d05ac2d240">KVO compliant properties</a> or object.</p><h3><strong>assign(to:on:)</strong></h3><p>‘<strong>assign(to:on:)</strong>’ is used when you want to set a given property each time a publisher produces a value. Let’s check this using some code.</p><pre>import Foundation<br>import Combine<br><br>/*<br> This is a Util function for logs.<br> Function will take a title of the topic and will execute the blocks<br> after printing.<br> */<br><br>public func myLearningCode(of title: String,<br>                           execute: () -&gt; Void) {<br>    print(&quot;\n ***** Example of:&quot;, title, &quot;***** \n&quot;)<br>    execute()<br>}<br><br>myLearningCode(of: &quot;assign(to:on:) subscriber&quot;) {<br>    <br>    // 1<br>    class Human {<br>        var name: String = &quot;&quot; {<br>            didSet {<br>                // 5<br>                print(&quot;Current name assigned is \(name) \n&quot;)<br>            }<br>        }<br>    }<br>    <br>    // 2<br>    let object = Human()<br>    <br>    // 3<br>    let publisher = [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Nikunj&quot;].publisher<br>    <br>    // 4<br>    _ = publisher<br>        .assign(to: \.name, on: object)<br>}</pre><ol><li>Simple class ‘Human’ with a property called ‘name’. We have used ‘<strong>didSet</strong>’ observer to print values when changed.</li><li>Created an object for our class.</li><li>Created a Publisher with string values from an array.</li><li>Used ‘<strong>assign(to:on:)’ </strong>subscriber on our publisher of step #3. Make a note that we are passing object reference to subscriber. <strong>‘\.name’ </strong>value gives access to the property. Notice the return value of ‘<strong>assign(to:on:)’ </strong>which is a cancellable subscription object.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RjSSSHnoXFjOLpL1JzuJdA.png" /></figure><p>5. Prints the value received from assign subscriber to name property of the object.</p><p>Take a pause and think about possible output. Let’s run and check the real output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eu-CTGTaGNfCpDfSaP-nDA.png" /></figure><p><strong><em>Note that, we are passing a created object to the subscription at step #4. That subscription will preserve strong reference cycle with the passed object until publisher of that subscription doesn’t send a completion event either with success or failure.</em></strong></p><p>The <strong>assign(to:on:) </strong>function is particularly beneficial when developing applications using <em>UIKit</em> or <em>AppKit</em>, as it allows for direct assignment of values to objects of <em>labels, text views, checkboxes, and other user interface elements</em>.</p><h3><strong>assign(to:)</strong></h3><p>There is a variation of the assign that <strong><em>you can use to republish values emitted by a publisher through another property</em></strong> marked with the <strong>@Published</strong> property wrapper.</p><p>To try this add this new example to your playground.</p><pre>import Foundation<br>import Combine<br><br>/*<br> This is a Util function for logs.<br> Function will take a title of the topic and will execute the blocks<br> after printing.<br> */<br><br>public func myLearningCode(of title: String,<br>                           execute: () -&gt; Void) {<br>    print(&quot;\n ***** Example of:&quot;, title, &quot;***** \n&quot;)<br>    execute()<br>}<br><br>myLearningCode(of: &quot;assign(to:) subscriber&quot;) {<br>    <br>    // 1<br>    class Human {<br>       @Published var name: String = &quot;Default&quot;<br>    }<br>    <br>    // 2<br>    let object = Human()<br>    <br>    // 3<br>    object.$name.sink { receivedValue in<br>        print(&quot;Current name assigned is \(receivedValue) \n&quot;)<br>    }<br>    <br>    // 4<br>    let namePublisher = [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Nikunj&quot;].publisher<br>    <br>    // 5<br>    namePublisher.assign(to: &amp;object.$name)<br>}</pre><ol><li>Simple class ‘<em>Human</em>’ with a ‘<strong>@Publised</strong>’ property ‘<em>name</em>’ having a ‘<em>Default</em>’ value. <br><strong><em>When we mark any property ‘Published’ it will automatically get its own Publisher.</em></strong> <strong><em>All subscriber will get an event when value of this property gets changed.</em></strong></li><li>Created an object for out class Human.</li><li>At this step, we are using Publisher of the Property ‘name’ with ‘sink’ subscriber to print its value when anyone assign anything to this property. <br>‘$’ sign we have used before property ‘<em>name</em>’ helps us to access <strong><em>default Publisher</em></strong> available for a ‘<strong>@<em>Published</em></strong>’ propert</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*9Okpj69fDnazSOnMZ0sdGg.png" /></figure><p>4. We have created a String publisher from an array so we can emit our string events.</p><p>5. ‘<strong>assign</strong>’ subscriber is used on our created ‘namePublisher’ to assign published value directly to a ‘<strong>@Published</strong>’ property. <br>if you notice, when we try to use <strong>‘assign(to:)’, </strong>we are not getting any return value from it. <strong><em>Its lifecycle is handled internally and get destroyed automatically once published property on which it is assigned, gets </em>deinitialized<em>. </em></strong>Notice usage of <strong>‘&amp;’</strong> which suggests <strong><em>pass by reference</em></strong> of the object value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1S5nK483OjAIykEd2d6s-w.png" /></figure><p>Let’s run and see the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Cppv3FHmti1-MhVBaZUkA.png" /></figure><h3>Summary</h3><ul><li>“<strong>assign</strong>” subscriber has two variants: <strong>assign(to:on:) </strong>and <strong>assign(to:)</strong></li><li>Emitted value from any publisher can directly been assigned to properties.</li><li><strong>assign(to:on:) </strong>will return a cancellable subscription object and also hold strong reference to the object passed for ‘on’ property.</li><li>‘<strong>@Published</strong>’ property will have its own Published attached with it by default.</li><li><strong>assign(to:) </strong>doesn’t return any subscription object and manage its lifecycle internally with the assigned ‘<strong>@Published</strong>’ property’s life cycle.</li></ul><p>We have seen ‘ASSIGN’ subscriber working, we will deep dive into default protocols of the <strong>Publisher, Subscriber and Subscription </strong>in the next article. Stay tuned with the combine <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><p>Feel free to <a href="https://nikunj-joshi.medium.com/"><strong>follow me</strong></a> to stay updated with the upcoming articles.</p><p>Thank You. Cheers!</p><p><strong>#Pre-Requisite<br></strong><em>Intermediate level of the swift language / iOS is required for this Combine Article series.</em></p><p><strong>#Credits</strong></p><p><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=358e4fe25303" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Combine — ‘JUST’ Publisher]]></title>
            <link>https://nikunj-joshi.medium.com/swift-combine-just-publisher-51e7f9051438?source=rss-4dd996182143------2</link>
            <guid isPermaLink="false">https://medium.com/p/51e7f9051438</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[combine-framework]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[N!kunj Joshi]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 13:52:54 GMT</pubDate>
            <atom:updated>2023-01-21T07:14:29.246Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Combine — ‘JUST’ Publisher</h3><p>In the previous <a href="https://medium.com/@nikunj-joshi/swift-combine-subscription-example-7259204ae8ea">article</a>, we have learnt about how to create a subscription using publisher and subscriber with notification centre example. If you wish to revise feel free to revisit the <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSUUXZFsAJuMvZwh0V1R4A.png" /></figure><p><strong><em>‘Unlimited Demand’ — </em></strong>As its name suggests, SINK subscriber follows rule of <em>unlimited demand</em>. Whenever any publisher emits any event ‘SINK’ subscriber will always receive it unless subscription is cancelled or completed.</p><p>Many times we face the scenario where we only want to convey single event and our work for that task is done. e.g. We are developing a chatting application and we have a service where we want to convey either sent message is ‘read’ by the receiver or not. This situation demand a Publisher which emits only single event and its task is done. <strong><em>‘JUST’ publisher from combine exactly provides this behaviour.</em></strong></p><p>Let’s check how ‘JUST’ publisher works by some coding. Copy paste below skeleton code with ‘Just Publisher’ title.</p><pre>import Foundation<br>import Combine<br><br>/*<br> This is a Util function for logs.<br> Function will take a title of the topic and will execute the blocks<br> after printing.<br> */<br><br>public func myLearningCode(of title: String,<br>                           execute: () -&gt; Void) {<br>    print(&quot;\n ***** Example of:&quot;, title, &quot;***** \n&quot;)<br>    execute()<br>}<br><br>myLearningCode(of: &quot;Just Publisher&quot;) {<br>    <br>}</pre><p>Add below code lines for Publisher and subscriber.</p><pre>myLearningCode(of: &quot;Just Publisher&quot;) {<br>    <br>    // 1<br>    let singleEventPublisher = Just(&quot; ** Event from &#39;Just&#39; publisher **&quot;)<br>    <br>    // 2<br>    _ = singleEventPublisher.sink { completion in<br>        <br>        // 4<br>        print(&quot;Received completion \(completion) \n&quot;)<br>        <br>    } receiveValue: { receivedValue in<br>        <br>        // 3<br>        print(&quot;Received a value \(receivedValue)&quot;)<br>        <br>    }<br>}</pre><p>Try to run and see what is the output.</p><h4>Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iC3dqJHABZlhj8i32_P_mg.png" /></figure><p>Let’s decode the working of this code.</p><ol><li>We are creating a ‘Just’ publisher by providing a event with a String value.</li><li>Using our created publisher, we are using ‘sink’ subscriber to create a subscription. We are using ‘receiveValue’ as well as ‘completion’ blocks from ‘sink’ subscriber.</li><li>When publisher will publish an event, we will get callback here and we have put a print statement for the reference.</li><li>When publisher will send a completion, we will get callback in this closure block.</li></ol><p>Remember, ‘<strong><em>JUST’ publisher will emit event for any subscriber only once and then completion will be sent</em></strong>. If same publisher emits other event for the different subscriber, older one will not get any event.</p><p><em>Let’s try to add one more subscription in our code and see.</em></p><pre>myLearningCode(of: &quot;Just Publisher&quot;) {<br>       <br>    // 5<br>    _ = singleEventPublisher.sink { completion in<br><br>        // 7<br>        print(&quot;Received completion \(completion) for subscription2 \n&quot;)<br><br>    } receiveValue: { receivedValue in<br><br>        // 6<br>        print(&quot;** Received a value \(receivedValue) for subscription2 **&quot;)<br><br>    }<br>}</pre><p>5. Apart from our older subscription at Step #2, we are creating a new subscription using a ‘sink’ subscriber.</p><p>6. Received value block for the newer subscription (Step #5)</p><p>7. Completion event block for the newer subscription (Step #5)</p><p>At this point, our whole code is having a Publisher and two subscribers. <strong><em>Take a minute pause and think what should be the our output ! ! !</em></strong></p><h4>Full Code</h4><pre>myLearningCode(of: &quot;Just Publisher&quot;) {<br>    <br>    // 1<br>    let singleEventPublisher = Just(&quot; ** Event from &#39;Just&#39; publisher **&quot;)<br>    <br>    // 2<br>    _ = singleEventPublisher.sink { completion in<br>        <br>        // 4<br>        print(&quot;Received completion \(completion) \n&quot;)<br>        <br>    } receiveValue: { receivedValue in<br>        <br>        // 3<br>        print(&quot;Received a value \(receivedValue)&quot;)<br>        <br>    }<br>    <br>    // 5<br>    _ = singleEventPublisher.sink { completion in<br><br>        // 7<br>        print(&quot;Received completion \(completion) for subscription2 \n&quot;)<br><br>    } receiveValue: { receivedValue in<br><br>        // 6<br>        print(&quot;** Received a value \(receivedValue) for subscription2 **&quot;)<br><br>    }<br>}</pre><h4>Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4LcG_Y6RaVACBlZwGRd_Og.png" /></figure><p>If you see output, both subscribers have received only one event from the publisher.</p><p><strong><em>Ideally, after the creation of our second subscription at step number #5, our first subscription should also receive events from the publisher as it is still not cancelled. This is because of the Publisher type being ‘JUST’, so it is sending event and a completion block only once per subscriber.</em></strong></p><h4>Summary</h4><p>we have seen how ‘JUST’ publisher works with different subscriptions. I hope, this clears the nature of ‘JUST’ publisher. That’s it for the article. <strong><em>Remember the silver line for the ‘JUST’ publisher : “It will send event only once per subscriber followed by the completion”</em></strong></p><p>We have seen ‘JUST’ publisher working, we will learn ‘<strong>ASSIGN</strong>’ subscriber in the next article. Stay tuned with the combine <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><p>Feel free to <a href="https://nikunj-joshi.medium.com/"><strong>follow me</strong></a> to stay updated with the upcoming articles.</p><p>Thank You. Cheers!</p><p><strong>#Pre-Requisite<br></strong><em>Intermediate level of the swift language / ios is required for this Combine Article series.</em></p><p><strong>#Credits</strong></p><p><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51e7f9051438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Combine — Subscription Example]]></title>
            <link>https://nikunj-joshi.medium.com/swift-combine-subscription-example-7259204ae8ea?source=rss-4dd996182143------2</link>
            <guid isPermaLink="false">https://medium.com/p/7259204ae8ea</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[combine-framework]]></category>
            <category><![CDATA[swift-combine]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[N!kunj Joshi]]></dc:creator>
            <pubDate>Thu, 19 Jan 2023 09:03:10 GMT</pubDate>
            <atom:updated>2023-01-20T10:25:47.636Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Combine — Subscription Example</h3><p>In the previous <a href="https://medium.com/@nikunj-joshi/swift-combine-basics-572752734d2c">article</a>, we have learnt about Combine Framework basics. If you wish to revise feel free to revisit the <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1wRJs49zZDF-pZ1sarsIg.png" /></figure><h3>Subscription</h3><p>When we say subscription, it always needs a Publisher and subscriber/s to complete it. Either publisher or subscriber doesn’t have its own significance without each other.</p><p>Let’s check subscription example with code. <em>We will use swift playground for our coding practices. Create a new workspace (Xcode -&gt; File -&gt; New -&gt; Workspace) in xcode, so we can organise our code snippets nicely.</em></p><p>Create a swift playground with your convenient name.</p><pre>import Foundation<br>import Combine<br><br>/*<br> This is a Util function for logs.<br> Function will take a title of the topic and will execute the blocks<br> after printing.<br> */<br><br>public func myLearningCode(of title: String,<br>                           execute: () -&gt; Void) {<br>    print(&quot;\n ***** Example of:&quot;, title, &quot;***** \n&quot;)<br>    execute()<br>}<br><br>// 1<br>myLearningCode(of: &quot;Subscription&quot;) {<br>    <br>}</pre><ol><li><em>We have called our logger function with title ‘Subscription’, so it will print logs with appropriate label. Copy above code into playground and run it, you should see below output into Debug area.</em></li></ol><pre>Debug Output:<br><br> ***** Example of: Subscription ***** </pre><p>Classic example of subscription we use during day to day app develpment is Notifications. We will have one publisher which will publish the notification event and our app will be a subscriber, which will receive emitted notifications.</p><p>Add below code by continuing our example</p><pre><br>// 1<br>myLearningCode(of: &quot;Subscription&quot;) {<br><br>    // 2<br>    let event = Notification.Name(&quot;Notification at \(Date().ISO8601Format())&quot;)<br><br>    // 3<br>    let center = NotificationCenter.default<br><br>    // 4<br>    let publisher = center.publisher(for: event, object: nil)<br>    <br>}</pre><p>2. <em>We need some ‘event’ to publish. Event can be any data / process result or api call result to publish. We have created a ‘Notification’ event with some name.</em></p><p>3. <em>‘NotificationCenter.default’ is used as a publisher source.</em></p><p>4. <em>We have created a Publisher using our notification event we have created. This publisher will be subscribed by some subsriber to receive its events.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQhM6GszerLxwyaSzsxjew.png" /></figure><p>Now, let’s try to apply sink subscriber on our created publisher, If you can <a href="https://medium.com/@nikunj-joshi/swift-combine-basics-572752734d2c"><strong>recall</strong></a><strong> </strong>our discussion, SINK subscriber provides two callbacks, ‘<strong>receivedValue</strong>’ and ‘<strong>receiveCompletion</strong>’. We will use ‘<strong>receiveValue</strong>’ callback for this tutorial.</p><p>Let’s continue adding below code in our function.</p><pre>myLearningCode(of: &quot;Subscription&quot;) {<br><br>// 5<br>let subscription = publisher.sink { notification in<br><br>        // 6<br>        print(notification.name.rawValue)<br>        print(&quot;Notification received from a publisher!&quot;)<br>    } <br>}</pre><p>5. We have publisher ready with us, now its time to add subscriber so we can create a ‘subscription’. We have used ‘SINK’ subscriber with received value completion. Syntax is using swift short hand annotation for the closure.</p><p>6. On receiving any event, control will return to the ‘receiveValue’ closure block where we are printing some statements.</p><pre>myLearningCode(of: &quot;Subscription&quot;) {<br><br>    // 7<br>    center.post(name: event, object: nil)<br><br>    //8 <br>    subscription.cancel()<br>}</pre><p>7. Now it’s time to emit / publish some events, so we have posted a notification event we have created previously. On this emission of event, control flow will transferred to ‘sink’ subscriber’s callback closure.</p><p>8. This shows how we can cancel our subscription.</p><h4>Full Code</h4><pre>import Foundation<br>import Combine<br><br>/*<br> This is a Util function for logs.<br> Function will take a title of the topic and will execute the blocks<br> after printing.<br> */<br><br>public func myLearningCode(of title: String,<br>                           execute: () -&gt; Void) {<br>    print(&quot;\n ***** Example of:&quot;, title, &quot;***** \n&quot;)<br>    execute()<br>}<br><br>// 1<br>myLearningCode(of: &quot;Subscription&quot;) {<br><br>    // 2<br>    let event = Notification.Name(&quot;Notification at \(Date().ISO8601Format())&quot;)<br><br>    // 3<br>    let center = NotificationCenter.default<br><br>    // 4<br>    let publisher = center.publisher(for: event, object: nil)<br><br>    // 5<br>    let subscription = publisher.sink { notification in<br><br>        // 6<br>        print(notification.name.rawValue)<br>        print(&quot;Notification received from a publisher!&quot;)<br>    }<br><br>    // 7<br>    center.post(name: event, object: nil)<br><br>    //8 <br>    subscription.cancel()<br>    <br>}</pre><p><strong><em>Run above function code and your output should be like this.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDN4Y8xUiZsZ-0W2tIoDAQ.png" /></figure><h3>Summary</h3><p>In this basic coding tutorial, we have seen how we can create a subscription and use it. We have created a publisher and a subscriber. We have also explored how to handle emitted event by the Publisher.</p><p>We will explore ‘<strong>Just</strong>’ publisher in the next article. Stay tuned with the combine <a href="https://medium.com/@nikunj-joshi/list/learn-combine-framework-the-smart-way-ab9e6919d5f0">learning series</a>.</p><p>Feel free to <a href="https://nikunj-joshi.medium.com/"><strong>follow me</strong></a> to stay updated with the upcoming articles.</p><p>Thank You. Cheers!</p><p><strong>#Pre-Requisite<br></strong><em>Intermediate level of the swift language / ios is required for this Combine Article series.</em></p><p><strong>#Credits</strong></p><p><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7259204ae8ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>