<?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 Shail Patel on Medium]]></title>
        <description><![CDATA[Stories by Shail Patel on Medium]]></description>
        <link>https://medium.com/@shail.patel.mi?source=rss-2cca5666e767------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*WZ6kcxUuwRtAl51ZZXGP9w.jpeg</url>
            <title>Stories by Shail Patel on Medium</title>
            <link>https://medium.com/@shail.patel.mi?source=rss-2cca5666e767------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:42:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shail.patel.mi/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[Saying hello to UICollectionView compositional layout]]></title>
            <link>https://medium.com/mindful-engineering/saying-hello-to-uicollectionview-compositional-layout-fd90562919b?source=rss-2cca5666e767------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd90562919b</guid>
            <category><![CDATA[declarative-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <dc:creator><![CDATA[Shail Patel]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 13:17:45 GMT</pubDate>
            <atom:updated>2021-04-02T05:40:38.221Z</atom:updated>
            <content:encoded><![CDATA[<h3>Saying Hello to UICollectionView Compositional Layout</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vz_TsW_FpzxhHeT-" /><figcaption>Photo by <a href="https://unsplash.com/@ivybarn?utm_source=medium&amp;utm_medium=referral">Ivy Barn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the WWDC-2019 Apple introduced some great features and frameworks. All developers are focusing on new frameworks and features like <a href="https://www.mindinventory.com/blog/swiftui-apple-newest-ui-framework/">SwiftUI</a>, Combine, RealityKit, etc, and try to figure out what they can do with it.</p><p>There are many small but very helpful features for existing apps that somehow didn’t get the attention of most developers and one of them is <strong>UICollectionViewCompositionalLayout<em>.</em></strong></p><p>All of us know we are using UITableView and UICollectionView everywhere for Application UI. UICollectionView is evolved from UITableView, and for more complex UICollectionView we have to use UICollectionViewFlowLayout or create some custom one extending UICollectionViewLayout. But stop! Have you ever tried to do that? If yes then you would probably be knowing that using this takes some extra effort, especially if you want to achieve nice behaviour.</p><p>All these hard things are stopping most developer to create this on their own and use the third-party libraries to fulfill their needs. That’s why Apple has introduced UICollectionViewCompositionalLayout and this class begins the era of declarative programming. I know you are excited to learn this new way to introduce UICollectionView.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F10474493&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fexcited-hockey-kid-gif-10474493&amp;image=https%3A%2F%2Fmedia.tenor.com%2Fimages%2Ff2f9c9650472cfe059c3e7bed89fc84e%2Ftenor.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/e789790752fcea7fd4b74ebdd0549773/href">https://medium.com/media/e789790752fcea7fd4b74ebdd0549773/href</a></iframe><h3>Introduction</h3><p>Compositional layouts are a declarative kind of API that allows us to build large layouts by stitching together smaller layout groups. Compositional layouts have a hierarchy that consists of Item, Group, Sections, and Layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sa6UsaL916EtZ4WToY-FbQ.png" /><figcaption>Image credits: <a href="https://developer.apple.com/documentation/uikit/views_and_controls/collection_views/layouts">Apple</a></figcaption></figure><p>To build any compositional layout, the following four classes need to be implemented:</p><ul><li><strong>NSCollectionLayoutSize:</strong> The width and height dimensions are of the type <strong>NSCollectionLayoutDimension</strong> which can be defined by setting the fraction width/height of the layout (percentage relative to its container), or by setting the absolute or estimated sizes.</li><li><strong>NSCollectionLayoutItem: </strong>This is your layout’s cell that renders on the screen based on the size.</li><li><strong>NSCollectionLayoutGroup:</strong> It holds the <strong>NSCollectionLayoutItem</strong> in either horizontal, vertical, or custom forms.</li><li><strong>NSCollectionLayoutSection</strong>: This is used to initialise the section by passing along the <strong>NSCollectionLayoutGroup.</strong> Sections eventually compose the compositional layouts.</li></ul><h3>Implementation</h3><p>In this project, I have used the <strong>UICollectionViewCompositionalLayout</strong> with <strong>UICollectionViewDiffableDataSource</strong>. You can use the normal collection to display the content instead of CollectionViewDiffableDataSource. In this project, we are mainly focusing on <strong>UICollectionViewCompositionalLayout</strong> so we will not discuss <strong>UICollectionViewDiffableDataSource</strong>.</p><p>I’m going to assume that you have already got a collection view setup, possibly with Diffable DataSource. In this project, we are using a collection cell with an image. So let’s implement <strong>UICollectionViewCompositionalLayout.</strong></p><p>First, create one method returning UICollectionViewCompositionalLayout. You have to assign that method to <strong>collectionViewLayout</strong> in the initialization method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dbbbdc1eb2c4ac2501cad20b9e1193a/href">https://medium.com/media/5dbbbdc1eb2c4ac2501cad20b9e1193a/href</a></iframe><p>You can see from the above method <strong>UICollectionViewCompositionalLayout </strong>initializer takes an instance of NSCollectionLayoutSection. In other words, a layout is built using sections. These sections are built using NSCollectionLayoutGroupinstances. A single section can contain multiple groups as well. Groups are considered to be the biggest workhorse of a compositional layout. You will typically do most configuration work on groups.</p><p>Here we have used <strong>NSCollectionLayoutGroup.horizontal </strong>to create the layout group. By making the layout group horizontal all items added to the group will be positioned horizontally. This means that the group will position items on the horizontal axis until it has filled up its width, and then it starts positioning items on the next “line” until that contains as many items as can be fit in the group’s width and so forth.</p><p>Here we have used <strong>fraction</strong> width and height for <strong>NSCollectionLayoutSize, </strong>which<strong> </strong>means it will fractionally set width and height according to device width and height. We can also use absolute and estimated height and width as well. <strong>Absolute</strong> will provide an exact height and width. By using <strong>estimated</strong> will be determined when the content is rendered. There is one restriction for <strong>estimated </strong>is that you must not set contentInsets for element otherwise, Layout will warn you and won’t draw respectively. You can play with this all sizes and check the changes for more understanding.</p><p>You can see that by implementing this you have started the collection to give some layout but still, there is no space between two items, groups, or sections. So let’s add some space between them.</p><h4>Adjusting the spacing between items, groups, and sections</h4><p>There are two possible ways to give the space to your collection view cells.</p><ol><li>Assign edge insets on the items, groups, or sections.</li><li>Assign a spacing between individual items and groups.</li></ol><p>By using edge insets you can apply like below.</p><p>item.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8)</p><p>You can also provide spacing using the following code.</p><p>group.interItemSpacing = .fixed(15)</p><p>Now it looks good after providing the spacing between items, groups. But still, if I want some more complex UI like one image as full width and then below there are three images in one group and then again repeat that group. Let’s see how can we implement that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f3d5e9fdb0f0a21e8b8537c73fa4c8c/href">https://medium.com/media/2f3d5e9fdb0f0a21e8b8537c73fa4c8c/href</a></iframe><p>You can see from the above code there are many changes than before. Let’s see one by one.</p><ol><li>We have created a large item that we have to put on the upper side of the group. And provide the edge insets.</li><li>We have created a small item that we have to put on the lower side of the group. And provide the edge insets.</li><li>Now we have created one group for bottom implementation and assign three items in that group.</li><li>Then we have created one group for full implementation, in that we have assigned two items first top item and second bottom group.</li><li>Then create a section with that final group and using that section created the final layout.</li></ol><p>By implementing this code you can see some beautiful and complex grid like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*7N2n2PwYoNcUDZzjIgpYeA.png" /></figure><p>That’s it you have implemented your first project with <strong>UICollectionViewCompositionalLayout.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FFNJ6MX0nn8lfW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FFNJ6MX0nn8lfW%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FFNJ6MX0nn8lfW%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="234" frameborder="0" scrolling="no"><a href="https://medium.com/media/3572ce3be8a6dc26c5a6075cc9ee6ef1/href">https://medium.com/media/3572ce3be8a6dc26c5a6075cc9ee6ef1/href</a></iframe><h3>Conclusion</h3><p>We have seen how powerful <strong>UICollectionViewCompositionalLayout </strong>is, but there is a lot more in UICollectionViewCompositionalLayout. We will cover that some other day. Till then enjoy coding and play with this new feature in UICollectionView.</p><p>If you have any questions then feel free to ask in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd90562919b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindful-engineering/saying-hello-to-uicollectionview-compositional-layout-fd90562919b">Saying hello to UICollectionView compositional layout</a> was originally published in <a href="https://medium.com/mindful-engineering">Mindful Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saying hello to Combine framework (API Call & Parsing) — Part-2]]></title>
            <link>https://medium.com/mindful-engineering/saying-hello-to-combine-framework-api-call-parsing-part-2-e412dc649664?source=rss-2cca5666e767------2</link>
            <guid isPermaLink="false">https://medium.com/p/e412dc649664</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[diffable-data-sources]]></category>
            <dc:creator><![CDATA[Shail Patel]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 10:35:19 GMT</pubDate>
            <atom:updated>2019-12-26T05:08:39.448Z</atom:updated>
            <content:encoded><![CDATA[<h3>Saying hello to Combine framework (API Call &amp; Parsing) — Part-2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2RFu-UkuGU30VpDs" /><figcaption>Photo by <a href="https://unsplash.com/@ben_wong_31?utm_source=medium&amp;utm_medium=referral">Benjamin Wong</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome back to this series of Combine framework. I hope the first part of this series clears the power of Combine in the development world.</p><p>In this second part, we will discuss Publisher, Subscribers, Operators, and Subjects briefly, and also see how to call API using Combine, and also discuss one very important topic called Diffable Datasource.</p><p>If you didn’t read the first part of this series then I highly recommend you to read the first part first, because the basics of Combine is described in the first part of this series. <a href="https://medium.com/mindful-engineering/saying-hello-to-combine-framework-part-1-30d9c07210df">Saying hello to Combine framework — Part-1</a>.</p><h3>Publisher</h3><p>We discussed the basics of Publisher in the first part, Now let’s check some of the in-built Publishers which combine provides.</p><h4>Just</h4><p>Just is a publisher that emits the output to all the subscribers once and then finish. A Just gives only one output. A Just publisher always produces a value, which means a Just publisher can’t fail with an error.</p><p>You can also use a Just publisher to replace the Catch statement for publishers. You can pass any value with a Just publisher, like <strong>Just(“example”)</strong>.</p><h4>Future</h4><p>Future is a publisher that eventually produces a single value then finishes or fails. It’s ideal to use when you want to make a single request or get a single response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da060b554d1b35ef2fee982ac3d30cb1/href">https://medium.com/media/da060b554d1b35ef2fee982ac3d30cb1/href</a></iframe><p>You can see the example of Future publisher above. We are providing success and failure using promise. When you want multiple responses or multiple requests then I recommend you not to use Future publisher.</p><h4>Published</h4><p>Published is a type that publishes a property marked with an attribute. Publishing a property with the @Published attribute creates a publisher of this type.</p><p>You can access the publisher with the $ operator. We have already seen the use of @Published property in the first part.</p><h4>Empty</h4><p>Empty is a publisher that never publishes any values and optionally finishes immediately. You can create a ‘Never’ publisher which never produces the value and also never fails using Empty(completeImmediately: false).</p><p>Empty is useful when we want to return a publisher but don’t want to propagate any values. We can use Empty publisher like. let emptyPublisher = Empty&lt;String, Never&gt; .</p><p>There are some other publishers which are not much useful like Fail, Sequence, Deferred, ObservableObjectPublisher for this demo of API parsing. So that’s it for publishers. We will learn more about publishers in upcoming posts.</p><h3>Operators</h3><p>There are lots of operators in the Combine framework. We will discuss the ones which are important and used frequently.</p><h4>combineLatest</h4><p>combineLatest receives and combines the latest elements from two publishers. There are also available combineLatest3 and combineLatest4 for combining elements from three and four publishers.</p><p>You can mix different upstream publisher types into a single stream. We have seen the use of a combineLatest in the first part.</p><h4>merge</h4><p>merge receives and combines the latest elements from two publishers. It goes up to merge8. In all cases, the upstreams publishers are required to have the same output type, as well as the same failure type.</p><p>If you want to mix different upstream publisher types into a single stream, then you likely want to use either combineLatest or zip, depending on how you want the timing of values to be handled.</p><h4>zip</h4><p>zip receives and combines the latest elements from two publishers. There are also available zip3 and zip4 for combining elements from three and four publishers.</p><p>The only difference between combineLatest and zip is in cobineLatest if any of one publisher value changed the combineLatest perform actions, but zip performs an action if both the publisher value changes.</p><h4>assertNoFailuer</h4><p>A publisher that raises a fatal error upon receiving any failure, and otherwise republishes all received input. It is useful when you want to verify that no error occurs.</p><p>It will cause the program to terminate if the assert is violated. You can use this operator as below.</p><pre>.assertNoFailure()<br> <em>// OR</em> <br>.assertNoFailure(&quot;What could possibly go wrong?&quot;)</pre><h4>retry</h4><p>retry is an operator which is useful when any request fails and you want a case like if a request fails it will retry up to some number of tries.</p><p>You can use this operator like .retry(3) . In this, if the request fails it will try 3 times.</p><h4>debounce</h4><p>debounce collapses multiple values within a specified time window into a single value. debounce is useful in a case where you are filtering an array using request and you want the request to be sent if the user not entering some new data for some time like 0.5sec.</p><p>Using debounce you can reduce the number for the request. The operator takes a minimum of two parameters, an amount of time over which to debounce the signal and a scheduler on which to apply the operations.</p><p>There are many more operators that are there in the Combine framework, but some of them which are useful illustrated above.</p><h3>Subjects</h3><p>In the first part, we have seen the basics for Subjects in the Combine framework. Subjects are a special kind of Publisher that can insert values, passed from the outside, into the stream.</p><p>Subjects can be used to “inject” values into a stream, by calling .send() method. This is useful for integrating existing imperative code with Combine. A subject can also broadcast values to multiple subscribers.</p><p>If multiple subscribers are connected to a subject, it will fan out values to multiple subscribers when send() is invoked.</p><p>There are two types of subjects in the Combine framework CurrentValueSubject and PassthroughSubject. Both act like the same, but the main difference between both is CurrentValueSubject has the default value and PassthroughSubject does not have the default value.</p><p>When .send() method is called on CurrentValueSubject. It will send the value over the default value.</p><h4>Subscribers</h4><p>In the first part, we have seen the basics for Subscriber. In this part, we will see the in-build subscribers.</p><p>There are two subscribers named as assign and sink. assign applies values passed down from the publisher to an object defined by a keypath. The keypath is set when the pipeline is created. The example of assign is as follows.</p><pre><strong>.</strong>assign(to: \<strong>.</strong>isEnabled, on: signupButton)</pre><p>sink accepts a closure that receives any resulting values from the publisher. The example of the sink is as follows.</p><pre><strong>.</strong>sink { receivedValue <strong>in</strong>     <br>    print(&quot;The end result was \(String(describing: receivedValue))&quot;) <br>}</pre><p>Most other subscribers are part of different Apple frameworks. For example, nearly every control in SwiftUI can act as a subscriber. The View protocol in SwiftUI defines an .onReceive(publisher) function to use views as a subscriber.</p><h3>Diffable Datasource</h3><p>This year in WWDC Apple introduced one very important UI update called Diffable Datasource. Diffable Datasource is available for both UITableView and UICollectionView.</p><p>So all you were think UITableView and UICollectionView is so much power so what is the need for Diffable Datasource. Sometimes we all get some crash because of the index and some update, using Diffable Datasource that all errors will not occur.</p><p>Using UITableViewDiffableDataSource or UICollectionViewDiffableDataSource along with NSDiffableDataSourceSnapshot you can create safe, animate changes between two states without having to keep track of which records were added, moved, or deleted.</p><p>Diffable Datasource calculates the difference between two snapshots and applies these changes with an appropriate animation. Before iOS 13, this required a significant amount of code and often times we would just give up and call reloadData.</p><p>We will see it’s implementation in our demo. First, let discuss some basic requirements for use Diffable Datasource. The data we are working with has to be Hashable to work with snapshots. We can create datasource and snapshot like below.</p><pre>var datasource: UITableViewDiffableDataSource&lt;Section, Data&gt;!</pre><pre>var snapshot: NSDiffableDataSourceSnapshot&lt;Section, Data&gt;!</pre><p>You have to define the section and the Model which you want to pass and both must conform to Hashable protocol otherwise, you will encounter an error. That’s enough for Diffable Datasource for now, we will see more of in some time in this part with example.</p><p>Ok, enough of theory part lets start with an example.</p><h3>Example</h3><p>In this part, we will see the example of API calls using MVVM with Combine and Diffable Datasource for UITableView.</p><p>The API we will be using is available at “<a href="https://jsonplaceholder.typicode.com/users">https://jsonplaceholder.typicode.com/users</a>”. It is just a dummy API which sends back dummy results.</p><p>In this example, we are showing data coming from API into UITableView using Diffable Datasource.</p><p>Let’s start with the Service Manager class in which we will do the API calling functionality.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00271b78856e0c52a96629842ec968d6/href">https://medium.com/media/00271b78856e0c52a96629842ec968d6/href</a></iframe><p>Ok, so let’s understand what we have done in the ServiceManager class.</p><ol><li>We have created an enum for API failure condition. Here I created only one case you can create any number of the case you want.</li><li>Next, Let’s create a structure to parse the response from the API. Here we want to value and full response to pass. Here we use generic for value.</li><li>Now the actual API service method we have created. Here we used decodable for decoding the response. We are returning the publisher of type AnyPublisher&lt;Response&lt;T&gt;, Error&gt; . After creating dataTaskPublisher we decode the result using tryMap. Using JSONDecoder we are decoding the value from the result. Finally, we are returning value and response.</li></ol><p>Now let’s move to our model class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6248ff82b78dac98291f96b031a957d6/href">https://medium.com/media/6248ff82b78dac98291f96b031a957d6/href</a></iframe><p>What we just did with our model class?</p><ol><li>We are creating the model using structure confirming the Decodable and Hashable protocol.</li><li>Here we are confirming Decodable protocol because we are using JsonDecoder for decoding the values.</li><li>Here we are confirming Hashable protocol because we want to use the DiffableDatasource. As discussed earlier model must be Hashable to use DiffableDatasource.</li></ol><p>We have created the ServiceManager class and our model class now we have to create one user service class from which we are calling all API for the user class.</p><p>We are using MVVM pattern so for service we do not directly call APIs from the user class instead we are calling the APIs from UserService class. In UserService class we will fill the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fad7a82cb47edca2c5cf86e11d8f8b5/href">https://medium.com/media/3fad7a82cb47edca2c5cf86e11d8f8b5/href</a></iframe><p>What we just did?</p><ol><li>Here we are creating one method which returns AnyPublisher&lt;[UserModel], Error&gt; . And calls the API from ServiceManager class.</li><li>Using .map(\.value) we are filling the values in the model.</li></ol><p>Now when we have created the UserService class to call API, from where we are calling API from UserService class? So the answer is pretty simple ViewModel class. So for that, we are creating a class named UserViewModel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c26e8b6d22dd3efac397bf6cf3d2699/href">https://medium.com/media/5c26e8b6d22dd3efac397bf6cf3d2699/href</a></iframe><p>What we just did?</p><ol><li>Here we created one array for storing the values and filter the search result locally and created one publisher using CurrentValueSubject for passing the changes to the controller.</li><li>Using UserService class reference we are calling API.</li><li>Using sink subscriber, we are processing the result. We store the result in an array as well as pass the value in the CurrentValueSubject publisher using send .</li><li>And lastly, we are creating one function in which we filter array locally when the user searches anything and sends updated data.</li></ol><p>Now let’s start with the Controller class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad53814a5631ee7b3a506b8f8afa865e/href">https://medium.com/media/ad53814a5631ee7b3a506b8f8afa865e/href</a></iframe><p>What we just did?</p><ol><li>First, we created one enum for Section which we will use in DiffableDatasource.</li><li>Then we created datasource instance using UITableViewDiffableDataSource.</li><li>In the initialization method, we have setup datasource, Searchfield UI, getting user data from ViewModel, and according to that set the snapshot for DiffableDatasource.</li><li>Now let’s understand how we can set up the datasource for DiffableDatasource. So first we create a new datasource using UITableViewDiffableDataSource&lt;Section, UserModel&gt; . This is the section that we have created earlier. Here the notable point is that enum is by default Hashable so we don&#39;t need to use a Hashable protocol for that. After giving the table instance we get three values in Closure for a table, indexPath, and data. After that, we are creating table cell instance like before and assign value to that cell. So that’s it for setting DiffableDatasource for UITableView.</li><li>Now let’s discuss snapshot creation. First, we are creating a new snapshot using NSDiffableDataSourceSnapshot&lt;Section, UserModel&gt;() . Then we are assigning a section to this snapShot using snapshot.appendSections([.main]) , then we assign data to snapShot using snapshot.appendItems(users) . Finally, we apply this snapShot to datasource which we have created earlier using dataSource.apply(snapshot, animatingDifferences: true) . And you just created one snapshot.</li><li>Now let’s come back to get data from ViewModel. We are calling the method which we have created in ViewModel for getting data.</li><li>After getting data from ViewModel we use .sink to get the data and assign that data to created snapShot, and by doing this the data is filled in a table and you can see nice animation for inserting data into the table.</li><li>If you are thinking that you don’t have to use the Delegate method for a table because you used DiffableDatasource then you are wrong. Like you have to use didSelectRowAt method for a table using the Delegate. You can get the exact data for index using dataSource.itemIdentifier(for: indexPath) .</li></ol><p>That’s it, you just created one API parsing demo with MVVM using DiffableDatasource.</p><h3>Conclusion</h3><p>In this second part of the Combine framework post, I’ve demonstrated how you can use Combine for parsing API using MVVM.</p><p>I hope now the abilities of DiffableDatasource are very clear to you. The best thing about DiffableDatasource is we don’t have to bother for index related issues and for animation.</p><p>In the next part, we will discuss how we can use combine with SwiftUI.</p><p>Meanwhile, you can find full source code from the following GitHub Project.</p><p><a href="https://github.com/Mindinventory/CombinePart-2">Mindinventory/CombinePart-2</a></p><p>Stay tuned with Mindful Engineering, we will be posting more detailed posts regarding Combine and such other interesting stuff in upcoming weeks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e412dc649664" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindful-engineering/saying-hello-to-combine-framework-api-call-parsing-part-2-e412dc649664">Saying hello to Combine framework (API Call &amp; Parsing) — Part-2</a> was originally published in <a href="https://medium.com/mindful-engineering">Mindful Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saying hello to Combine framework — Part-1]]></title>
            <link>https://medium.com/mindful-engineering/saying-hello-to-combine-framework-part-1-30d9c07210df?source=rss-2cca5666e767------2</link>
            <guid isPermaLink="false">https://medium.com/p/30d9c07210df</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Shail Patel]]></dc:creator>
            <pubDate>Sat, 07 Dec 2019 14:00:41 GMT</pubDate>
            <atom:updated>2019-12-24T09:53:01.320Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Saying hello to Combine framework — Part-1</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QjEsv1A9RhKQbFOG" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This year in WWDC Apple introduced a lot of new stuff to the developer world. There were many new things like SwiftUI, Dark Mode and Catalyst, But the most interesting thing Apple introduced was the Reactive framework, called <a href="https://developer.apple.com/documentation/combine">Combine</a>. <em>This post is not for FRP(Functional Reactive Programming), so we can directly start with the Combine framework</em>. In this post, we will introduce you to Combine with one basic example.</p><p>In Apple’s words, Combine is:</p><blockquote>A declarative Swift API for processing values over time.</blockquote><h3><strong>When to use Combine</strong></h3><p>Combine is useful when you want immediate effect of an action. User interfaces fit very naturally into this pattern.</p><p>The classic example in functional reactive programming and user interfaces frequently shown form validation, where user events such as changing text fields, taps or mouse-clicks on UI elements make up the data being streamed. Combine takes this quite a bit further, enabling watching properties, binding to objects, sending and receiving higher level events from UI controls, and supporting integration with almost all of Apple’s existing API ecosystem.</p><h3><strong>Core Concepts</strong></h3><h4><strong>Publisher</strong></h4><p>Publisher is basically a provider of data, when it is available and requested. A publisher that hasn’t had any request yet will not provide any data. The basic block for publisher is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82d8b257e140aef64766b74ffc0a4e18/href">https://medium.com/media/82d8b257e140aef64766b74ffc0a4e18/href</a></iframe><p>From the above code snippet you can see that Publisher has two associated types Output and Failure. Output describes the data which is requested by the subscriber. And the failure defines any failure related to that data.</p><h4><strong>Subscriber</strong></h4><p>Another core concept of Combine is <em>Subscriber</em>. Subscriber is responsible for requesting data, accepting data and handling possible failures provided by a publisher. In combine the subscriber initiates the request for data, and controls the amount of data it receives. The basic block of subscriber is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/915d660c2b036618cc6e42534bc9b495/href">https://medium.com/media/915d660c2b036618cc6e42534bc9b495/href</a></iframe><p>From above block you can see that subscriber has two associated types Input and Failure. Input describes the type of data which is requested to Publisher. Failure defines the failure.</p><p>When you connect a subscriber to a publisher, both types must match: Output to Input and Failure to Failure.</p><h4><strong>Operators</strong></h4><p>Operator is an object that acts like both a subscriber and a publisher. Operators are classes that adopt the Subscriber protocol and Publisher protocol. They support subscribing to a publisher, and sending results to any subscriber. Operators can be used to transform both the types Output and Failure. To choose the perfect operator for your use is very essential otherwise it will give you an error.</p><h4><strong>Subjects</strong></h4><p>A subject is a publisher that you can use to “inject” values into stream, by calling its <em>send(_:)</em> method. This can be useful for adapting existing imperative code to the combine model.</p><h3><strong>Lifecycle of Publishers and Subscribers</strong></h3><ol><li>When the subscriber is attached to a publisher, it starts with a call to <em>subscriber(subscriber)</em>.</li><li>The publisher in turn acknowledges the subscriber calling <em>receive(subscription)</em>.</li><li>After the subscription has been acknowledged, the subscriber requests N (or fewer) values with <em>request(_ : Demand)</em>.</li><li>The publisher may then (as it has values) sends N (or fewer) values: <em>receive(_ : Input)</em>. A publisher should never send more than the demand requested.</li><li>Also after the subscription has been acknowledged, the subscriber can send a cancellation with <em>cancel()</em></li><li>A publisher may optionally send completion: <em>receive(completion:)</em>. A completion can be either a normal termination, or may be a .failure completion, optionally propagating an error type.</li></ol><p>Ok enough of theory, let’s start with some coding part!</p><h3><strong>Example</strong></h3><p>Here we are creating the form view in which there are three text fields like username, password and confirm password. There are two labels for validation of username and password. There is one button for submit which enabling and disabling of validating all the fields and it will change its color.</p><p>In this demo we are using the MVVM pattern. If you are not familiar with the MVVM pattern I suggest you to first check the <a href="https://medium.com/flawless-app-stories/how-to-use-a-model-view-viewmodel-architecture-for-ios-46963c67be1b">MVVM pattern</a>.</p><p>First of all, create one ViewController as FormVC and ViewModel for that ViewController named as FormViewModel. Now we are good to go, Let’s start our first combine project. It is important to import Combine before we start coding using Combine.</p><p>First create two subscribers in FormVC as shown below using AnyCancellable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8314ef6fd6569798704dc4f8a71860e6/href">https://medium.com/media/8314ef6fd6569798704dc4f8a71860e6/href</a></iframe><p>usernameSubscriber and passwordSubscriber are used to subscribe to the changes happening in respective textfields.</p><p>Now we will create validations in FormViewModel. First we are going to create three published property for username, password and confirm password like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ce32c73566844a8cf7bb7f40ec46205/href">https://medium.com/media/8ce32c73566844a8cf7bb7f40ec46205/href</a></iframe><p>Initially, all the fields are blank because we didn’t enter anything in that text fields. Published allows you to wrap a property and enabling you to get a publisher that triggers data updates whenever the property is changed.</p><p>Now we will create two publishers for publishing the username validation message and password validation message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3a3b736166cd7afad653ea3eb99bcd3/href">https://medium.com/media/e3a3b736166cd7afad653ea3eb99bcd3/href</a></iframe><p>There are two types for creating the publisher using subject. The first one is PassthroughSubject and another is CurrentValueSubject. Use CurrentValueSubject to publish whenever you update the subject’s underlying value. And use PassthroughSubject to publish values on-demand by calling its send(_:) method.</p><p>Now let’s add the validation messages on the username textfield.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a98a7b1c1d4b72b272519686394fe5f/href">https://medium.com/media/2a98a7b1c1d4b72b272519686394fe5f/href</a></iframe><p>What we just did?</p><ol><li>Here we are using <em>AnyPublisher&lt;String?, Never&gt;</em> means the output is optional <em>String</em> and the failure type is <em>Never</em>.</li><li>Here we used $ before username because we want the change to appear whenever the value is changed.</li><li>We are using map operator to do some operation according to output.</li><li>First we are checking for empty username validation.</li><li>If username is not empty then it must have at least 3 characters.</li><li>We are using <em>send(_:)</em> method on publisher to send the output to subscriber.</li><li>And in the last we are using <em>eraseToAnyPublisher()</em>. that will do type erasure on the chain of operators so the resulting signature is of type <em>AnyPublisher&lt;String?, Never&gt;</em>.</li></ol><p>Now let’s add the validation message on the password and confirm password textfield.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcb57a5f828b5701969df9de70f11f8a/href">https://medium.com/media/dcb57a5f828b5701969df9de70f11f8a/href</a></iframe><p>Here is what we just did:</p><ol><li>Here we are using <em>AnyPublisher&lt;String?, Never</em>&gt; means the output is optional string and the failure type is Never.</li><li>Here we used <em>CombineLatest</em> for combining the latest element from <em>password</em> and <em>confirmPassword</em> publishers.</li><li>Here we used $ before <em>password</em> and <em>confirmPassword</em> because we want the change to be notified whenever the value is changed.</li><li>Here we use <em>receive(on: RunLoop.main)</em> because we want to do the operation in main thread.</li><li>We are using map operator to do some operation according to output.</li><li>We are checking if both <em>password</em> and <em>confirmPassword</em> matched or not and if matches it must have length of 5 characters.</li><li>Then we send the output using <em>send(_:)</em> method.</li><li>Finally we use <em>eraseToAnyPublisher()</em> for output type assurance.</li></ol><p>Now if both username and password validation passes then we have to enable submit button and want to do ready form for submission.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/417083e9dcb560a1a681945eb16ab7bf/href">https://medium.com/media/417083e9dcb560a1a681945eb16ab7bf/href</a></iframe><p>What we just did?</p><ol><li>Here we are using <em>AnyPublisher&lt;(String?, String?)&gt;, Never&gt;</em> because we want to pass the username and password on the submit button so there are two option <em>String</em> for Output and Failure type is <em>Never</em>.</li><li>Here we used <em>CombineLatest</em> for combining the latest element from <em>validateUserName</em> and <em>validatePassword</em> publishers.</li><li>Finally we use <em>eraseToAnyPublisher()</em> for output type assurance.</li></ol><p>We completed validations. That’s it for View Model now let’s go to view controller.</p><p>First create instance of <em>FormViewModel</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b85588b0734df92e86890c6319e44a05/href">https://medium.com/media/b85588b0734df92e86890c6319e44a05/href</a></iframe><p>Now let’s bind the Published variable from <em>FormViewModel</em> to our textfields.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6d8484ada960f77d38921f266a56b4f/href">https://medium.com/media/e6d8484ada960f77d38921f266a56b4f/href</a></iframe><p>What we just did?</p><ol><li>Here I am using textfield’s EditingChanged method(@IBAction) for getting changes in textField, you can also use delegate methods as well.</li><li>After that we give the value of textfield’s text to FormViewModel published var so when the value of textfield change that publisher will be called.</li></ol><p>Now let’s create one method in which we can check for validation messages and display in label, as well do submit button enable and disable functionality. We have to call that method in viewDidLoad() .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b25cde9b26bc99fb12510e190dcc20e1/href">https://medium.com/media/b25cde9b26bc99fb12510e190dcc20e1/href</a></iframe><p>What we just did?</p><ol><li>First we are doing some operation on <em>userNameMessagePublisher</em> from ViewModel and show the message from that publishers output to username validation label.</li><li>We used “sink” subscriber for displaying the message in label.</li><li>In next step, we give that subscriber to <em>usernameSubscriber</em> which we have created in starting.</li><li>Same thing we did with <em>passwordMessagePublisher</em> and give it to <em>passwordSubscriber</em>.</li><li>Now using <em>readyToSubmit</em> Publisher of <em>FormViewModel</em> we are doing operation for submit button enabling and disabling as-well color changing of that button.</li><li>We are using map operator which returns nil if any value is nil. Checking against a nil value provides the boolean used to enable or disable the submit button.</li><li>Using sink subscriber we are receive boolean value and using that value we can change the color of button as-well change the state of button enable or disable.</li><li>The store method is available on the Cancellable protocol, which is explicitly set up to support saving off references that can be used to cancel a request.</li></ol><h3><strong>Conclusion</strong></h3><p>In this first part of Combine framework I’ve demonstrated how you can use Combine for validation using MVVM. The best thing about Combine is the deep integration with Swift Foundation. In the next part we will discuss about Publisher, Subscriber, Operators and Subjects in more details, and we will discuss some new points like integration with SwiftUI, Built-in publishers and subscribers and how we can use combine for API calling. There are much more to understand about Combine and we will cover all in this series of Combine framework.</p><p>You can find the second part of this series <a href="https://medium.com/mindful-engineering/saying-hello-to-combine-framework-api-call-parsing-part-2-e412dc649664">Saying hello to Combine framework (API Call &amp; Parsing) — Part-2</a> .</p><p>You can download the full source code from following GitHub Project.</p><p><a href="https://github.com/Mindinventory/CombinePart-1">Mindinventory/CombinePart-1</a></p><p>Here is the second part of this series <a href="https://medium.com/mindful-engineering/saying-hello-to-combine-framework-api-call-parsing-part-2-e412dc649664">Saying hello to Combine framework (API Call &amp; Parsing) — Part-2</a>.</p><p>Stay tuned with Mindful Engineering, we will be posting more detailed posts regarding Combine and such other interesting stuff in upcoming weeks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30d9c07210df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindful-engineering/saying-hello-to-combine-framework-part-1-30d9c07210df">Saying hello to Combine framework — Part-1</a> was originally published in <a href="https://medium.com/mindful-engineering">Mindful Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>