<?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 Kapil Choubisa on Medium]]></title>
        <description><![CDATA[Stories by Kapil Choubisa on Medium]]></description>
        <link>https://medium.com/@kkapilchoubisa?source=rss-364968580fc4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cJznd8O4Rt1pdVmrnyyxbQ.jpeg</url>
            <title>Stories by Kapil Choubisa on Medium</title>
            <link>https://medium.com/@kkapilchoubisa?source=rss-364968580fc4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:11:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kkapilchoubisa/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[Empowering My Python Journey: A Tale of Copilot Collaboration]]></title>
            <link>https://medium.com/@kkapilchoubisa/empowering-my-python-journey-a-tale-of-copilot-collaboration-ae6c11313c7d?source=rss-364968580fc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae6c11313c7d</guid>
            <category><![CDATA[gen-ai-tools]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[github-copilot]]></category>
            <dc:creator><![CDATA[Kapil Choubisa]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 13:59:29 GMT</pubDate>
            <atom:updated>2024-09-12T13:59:29.917Z</atom:updated>
            <content:encoded><![CDATA[<p>As a seasoned software professional with over 15 years of experience primarily in Objective-C and Swift, my journey into the world of Python was rather unexpected. While I had a theoretical understanding of technologies like React and Java, practical implementation had always eluded me. Despite architecting solutions for projects, which involved critical decisions on microservices, database selections, cloud infrastructure, and more, I rarely found myself hands-on with the actual coding.</p><p>However, circumstances can change rapidly in the tech industry. I found myself in a resource-constrained situation where I needed to dive into Java Spring Boot and Python development for a client project. With time constraints looming large and the pressure to deliver mounting, I turned to GitHub Copilot for assistance.</p><p>The task at hand was to rectify a situation where users in a system had been assigned the incorrect role (Admin), and the historical data needing correction was substantial. The solution required interfacing with another system through a limited set of APIs, without resorting to direct database queries.</p><p>With no prior experience in Python and my development team preoccupied with looming deadlines, I faced the challenge head-on. I decided to take matters into my own hands and write the script myself — my inaugural Python program after 34 years in the field.</p><p>Enter GitHub Copilot, my coding companion in this uncharted territory. Unsure of where to begin, I started by adding comments within my code:</p><pre># Get the configuration like GET_USER_API_URL, DEPROVISION_URL, PROVISION_URL, CLIENT_ID, CLIENT_SECRET and updatedByUser from config.yml</pre><p>With a simple comment, Copilot sprung into action, suggesting code snippets:</p><pre>import yaml<br><br>with open(&quot;config.yml&quot;, &#39;r&#39;) as ymlfile:<br>    config = yaml.safe_load(ymlfile)<br><br>GET_USER_API_URL = config[&quot;get_user_api_url&quot;]<br>DEPROVISION_URL = config[&quot;deprovision_url&quot;]<br>PROVISION_URL = config[&quot;provision_url&quot;]<br>CLIENT_ID = config[&quot;client_id&quot;]<br>CLIENT_SECRET = config[&quot;client_secret&quot;]<br>UPDATED_BY_USER = config[&quot;updated_by_user&quot;] </pre><p>The code generated by GitHub Copilot not only extracted the necessary variables from the YAML configuration file but also demonstrated promising functionality upon execution, validating its effectiveness.</p><p>Encouraged by this initial success, I proceeded to enhance my script with more functionalities, leveraging Copilot’s intelligent suggestions to streamline my coding process.</p><pre># Create a method to get all users from the user API with url and headers as parameters<br>def getAllUsers():<br>    headers = {<br>      &quot;Content-Type&quot; : &quot;application/json&quot;<br>    }<br>    response = request.get(GET_USER_API_URL, headers=headers)<br>    print(response.json())</pre><p>In response to my comment requesting a method to retrieve users from an API in the first line, Copilot promptly generated a function that incorporated the necessary HTTP headers and utilized the requests library to make the API call. The print(response.json()) line confirmed the successful retrieval of user data, demonstrating Copilot&#39;s ability to accelerate my coding workflow.</p><p>As I delved deeper into my Python script, I encountered the need to handle API responses more effectively. Notably, GitHub Copilot proved invaluable in guiding me through this unfamiliar terrain.</p><p>To refine the getAllUsers() method, I added a descriptive comment outlining the desired behavior:</p><pre># In case of error return empty list, in case of success, filter the list and keep only non admin users</pre><p>Copilot promptly updated the function to incorporate error handling and filtering based on user roles:</p><pre>def getAllUsers():<br>    headers = {<br>      &quot;Content-Type&quot; : &quot;application/json&quot;,<br>      &quot;client_id&quot;: CLIENT_ID,<br>      &quot;client_secret&quot;: CLIENT_SECRET<br>    }<br>    response = request.get(GET_USER_API_URL, headers=headers)<br>    # In case of error return empty list, in case of success, filter the list and keep only non admin users<br>    if response.status_code != 200:<br>        return []<br>    userList = response.json()<br>    return [user for user in userList if user[&quot;roleType&quot;] == &#39;Admin&#39;]</pre><p>This transformation not only addressed potential API errors by returning an empty list but also filtered the user data to exclude those with the ‘Admin’ role. Copilot’s responsiveness to my comments streamlined my coding process, enabling me to implement robust error handling and data filtering seamlessly.</p><p>Excited by the capabilities of GitHub Copilot, I proceeded to tackle the next challenge: updating user roles by deprovisioning and reprovisioning users through API calls.</p><p>As I began outlining the updateUser() function, Copilot intuitively recognized my intent and suggested the creation of API headers based on my previous usage:</p><pre>headers = {<br>    &quot;Content-Type&quot; : &quot;application/json&quot;,<br>    &quot;client_id&quot;: CLIENT_ID,<br>    &quot;client_secret&quot;: CLIENT_SECRET<br>}</pre><p>With Copilot’s guidance, I swiftly incorporated the necessary headers into the function structure by just adding the comment in the next line:</p><pre>def updateUser():<br>    headers = {<br>        &quot;Content-Type&quot; : &quot;application/json&quot;,<br>        &quot;client_id&quot;: CLIENT_ID,<br>        &quot;client_secret&quot;: CLIENT_SECRET<br>    }<br><br>    # Get all the users, iterate and call API to deprovision users with userId, roleType and updatedBy params<br>    allUsers = getAllUsers()<br>    for user in allUsers:<br>        deprovisionRequestPayload = {<br>            &quot;userId&quot;: user[&quot;userId&quot;],<br>            &quot;roleType&quot;: user[&quot;roleType&quot;],<br>            &quot;updatedBy&quot;: UPDATED_BY_USER<br>        }<br>        deprovisionRequestPayloadJson = json.dumps(deprovisionRequestPayload)<br>        response = request.delete(DEPROVISION_URL, data=deprovisionRequestPayloadJson, headers=headers)<br>        print(response.status_code)</pre><p>My excitement with GitHub Copilot continued to grow as I approached the task of refining the response handling in my script. Given that this was a one-time executable script, I aimed to enhance error management by logging failed user details while continuing to provision successful users.</p><p>To achieve this, I introduced two new list variables at the beginning of the updateUser() function:</p><pre>def updateUser():<br>    deprovisioningFailedFor = []<br>    provisioningFailedFor = []<br>    headers = {<br>      ....</pre><p>With these variables in place, I streamlined my approach by removing unnecessary print statements and focusing on error handling within the function:</p><pre>if response.status_code != 200<br>    deprovisioningFailedFor.append(user)</pre><p>GitHub Copilot adeptly recognized my intentions, seamlessly integrating the variable declarations and error-handling logic into the function structure.</p><p>This enhancement not only improved the clarity and efficiency of my script but also demonstrated Copilot’s remarkable ability to adapt to evolving coding requirements.</p><p>The refinement of my updateUser() function continued to unfold smoothly with the help of GitHub Copilot. After implementing error handling for failed API requests, I aimed to provision users with a specific role and update their details accordingly.</p><p>To achieve this, I introduced a continue statement to ensure the script proceeds to the next user in case of a successful provision. I also added a descriptive comment to highlight the purpose of the subsequent API call:</p><pre># Make API call to provision user with userId, roleType as Reader and updatedBy </pre><p>In a matter of milliseconds, Copilot generated the necessary code to execute this provision request effectively:</p><pre>provisionRequestPayload = {<br>    &quot;userId&quot;: user[&quot;userId&quot;],<br>    &quot;roleType&quot;: &quot;Reader&quot;,<br>    &quot;updatedBy&quot;: UPDATED_BY_USER<br>}<br>provisionRequestPayloadJson = json.dumps(provisionRequestPayload)<br>response = request.delete(PROVISION_URL, data=provisionRequestPayloadJson, headers=headers)<br>if response.status_code != 200:<br>    provisioningFailedFor.append(user)<br>    continue</pre><p>After refining and fine-tuning my script with GitHub Copilot’s assistance, I reached the culmination of my Python development journey. With all components in place, my script was primed and ready to execute the envisioned tasks.</p><p>Here’s the final version of my script, showcasing the integrated components and functionality achieved through collaboration with GitHub Copilot:</p><pre># Get the configuration like API URL, secrets, updatedByUser from config.yml<br>import yaml<br>import requests<br>import json<br><br>with open(&quot;config.yml&quot;, &#39;r&#39;) as ymlfile:<br>    config = yaml.safe_load(ymlfile)<br><br>GET_USER_API_URL = config[&quot;get_user_api_url&quot;]<br>DEPROVISION_URL = config[&quot;deprovision_url&quot;]<br>PROVISION_URL = config[&quot;provision_url&quot;]<br>CLIENT_ID = config[&quot;client_id&quot;]<br>CLIENT_SECRET = config[&quot;client_secret&quot;]<br>UPDATED_BY_USER = config[&quot;updated_by_user&quot;]<br><br># Create a method to get all users from the user API with URL and headers as parameters<br>def getAllUsers():<br>    headers = {<br>        &quot;Content-Type&quot; : &quot;application/json&quot;,<br>        &quot;client_id&quot;: CLIENT_ID,<br>        &quot;client_secret&quot;: CLIENT_SECRET<br>    }<br>    response = requests.get(GET_USER_API_URL, headers=headers)<br>    # In case of error return empty list, in case of success, filter the list and keep only non-admin users<br>    if response.status_code != 200:<br>        return []<br>    userList = response.json()<br>    return [user for user in userList if user[&quot;roleType&quot;] == &#39;Admin&#39;]<br><br>def updateUser():<br>    deprovisioningFailedFor = []<br>    provisioningFailedFor = []<br>    headers = {<br>        &quot;Content-Type&quot; : &quot;application/json&quot;,<br>        &quot;client_id&quot;: CLIENT_ID,<br>        &quot;client_secret&quot;: CLIENT_SECRET<br>    }<br><br>    # Get all the users, iterate and call API to deprovision users with userId, roleType, and updatedBy params<br>    allUsers = getAllUsers()<br>    for user in allUsers:<br>        deprovisionRequestPayload = {<br>          &quot;userId&quot;: user[&quot;userId&quot;],<br>          &quot;roleType&quot;: user[&quot;roleType&quot;],<br>          &quot;updatedBy&quot;: UPDATED_BY_USER<br>        }<br>        deprovisionRequestPayloadJson = json.dumps(deprovisionRequestPayload)<br>        response = requests.delete(DEPROVISION_URL, data=deprovisionRequestPayloadJson, headers=headers)<br>        if response.status_code != 200:<br>            deprovisioningFailedFor.append(user)<br>            continue<br><br>        # Make API call to provision user with userId, roleType as Reader, and updatedBy<br>        provisionRequestPayload = {<br>          &quot;userId&quot;: user[&quot;userId&quot;],<br>          &quot;roleType&quot;: &quot;Reader&quot;,<br>          &quot;updatedBy&quot;: UPDATED_BY_USER<br>        }<br>        provisionRequestPayloadJson = json.dumps(provisionRequestPayload)<br>        response = requests.delete(PROVISION_URL, data=provisionRequestPayloadJson, headers=headers)<br>        if response.status_code != 200:<br>            provisioningFailedFor.append(user)<br>            continue<br><br>updateUser()</pre><h3>Conclusion</h3><p>In conclusion, my exploration of Python development with GitHub Copilot has been transformative. Copilot’s ability to generate code based on context and comments streamlined my coding process, from implementing API calls to handling complex data filtering.</p><p>What sets Copilot apart is its intuitive understanding of intentions conveyed through comments, enabling collaborative coding in real-time. This AI-driven tool represents a paradigm shift in developer productivity, bridging the gap between concept and implementation.</p><p>As I reflect on this experience, GitHub Copilot emerges as a catalyst for creativity and efficiency in software development. It augments human ingenuity, propelling coding endeavors forward with remarkable precision and support.</p><p>In essence, GitHub Copilot embodies the future of coding assistance, empowering developers to navigate challenges confidently and explore new possibilities in the world of programming.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae6c11313c7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Background tasks in iOS]]></title>
            <link>https://medium.com/@kkapilchoubisa/background-tasks-in-ios-d92d0a51dc25?source=rss-364968580fc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d92d0a51dc25</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[background-mode]]></category>
            <category><![CDATA[background-task]]></category>
            <dc:creator><![CDATA[Kapil Choubisa]]></dc:creator>
            <pubDate>Tue, 05 Apr 2022 12:39:24 GMT</pubDate>
            <atom:updated>2022-04-08T09:24:39.329Z</atom:updated>
            <content:encoded><![CDATA[<p>Almost two years back, while working on an interesting client project, we were implementing a offline sync solution. Application was receiving data from a bluetooth enabled device and that data was inserted in local database. Later, the data should be uploaded to the server using a POST api. On successful upload of that data, we were suppose to mark a flag in our local database.</p><p>In order to explain the problem, let me show (in below diagram) the application states quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*WoDTxRo-3mva0oetGoVdcg.png" /></figure><p>Note: BecomeActive and ResignActive are not considered as this diagram is intended to show states and not the lifecycle methods.</p><p>With the help of above diagram, we know that application can perform flawlessly while in foreground. However, when user press home button, application enters in background and then developers need to write additional code to take things in their hands.</p><h3>Problem</h3><p>As mentioned earlier, our team had situation to make sure that each API call which get initiated should be completed and update database, even if application is moved to the background.</p><p>iOS normally allows your application to run in background state for 10 seconds and later it move to suspended state. The suspended state means that application is idle. Not killed but unable to perform any activity unless it is moved back to foreground or background state.</p><p>Generally, 10 seconds should be good enough for completing any API call for modern applications as API response time these days is in milliseconds. However, we wanted to delay the suspension of application and get the maximum background time or at least till our task is done.</p><h3>Application Background Task</h3><p>The UIBackgroundTask tells OS that application is performing a background activity and should delay the suspension until the task is completed or expired. This generally gives you 30 seconds (may change in OS upgrades, few years back it was 180 seconds).</p><p>You should finish your task within the extra time you get.</p><h4>How to do it?</h4><p>You can call beginBackgroundTask on UIApplication’s shared instance. This will provide you an UIBackgroundTaskIdentifier object. You should keep track of this object and call endBackgroundTask in the expiration handler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85a706c7b9481aa5de2eeb0976cc45a5/href">https://medium.com/media/85a706c7b9481aa5de2eeb0976cc45a5/href</a></iframe><p>The above code will end the task once the background task expires i.e roughly around 30 seconds. Now what if your task was actually completed at 15th second? This still keep your application in background for 30 seconds. Now that’s not a good tenant behaviour on a device.</p><p>So you should keep track of the identifier and call endBackgroundTask method once your task is completed i.e 15th second and let application suspend.</p><h4><strong>A task created should always end.</strong></h4><p>If you don’t end a task, this can lead the watchdog kill your application unexpectedly and that is going to be a crash for you. Definitely you don’t want this.</p><p>It is up to you to decide when to end the task. As mention above, you can end it once the desired job is completed or in the expiration block. I suggest to do it at both the places. Something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaea7499c92bc98c08a7721239fa1c69/href">https://medium.com/media/aaea7499c92bc98c08a7721239fa1c69/href</a></iframe><h4>Create one task for one job</h4><p>I have seen many developers using the beginBackgroundTask method in applicationDidEnterBackground lifecycle hook. This definitely work but don’t give you control over ending the task when the intended job is completed.</p><p>So, if you are calling multiple APIs or other operation, which you want to make sure that gets enough time, you should call the beginBackgroundTask method. You should also keep track of that task identifier, so that you can end it once job is done. Remember the watchdog is watching you.</p><h4>Can I get unlimited time?</h4><p>Or let me reframe it by asking “can I fool the OS?”. You might have an idea or may be not but I had it. I thought of calling the beginBackgroundTask method from the expiry block of the previous one to keep on getting 30 seconds. See below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a200c6c4bf46049fafe7f61ec5d385b5/href">https://medium.com/media/a200c6c4bf46049fafe7f61ec5d385b5/href</a></iframe><p>It doesn’t work that way. You try it with recursive or in a loop or as many as background task, there is a fix time you will get from OS and it won’t exceed from that. E.g. if you create one task as soon as you enter in background and you got 30 seconds, after 10 seconds you create another task and you will not get more than 20 seconds now because 10 seconds are already passed since application went in background.</p><h3>How to bring application back from suspended state?</h3><p>This could definitely be the next question and the easiest answer is when user bring the application back in foreground. However, there are other ways by which application can come out of suspended state and be in background state without user’s intervention.</p><ul><li>Events from BackgroundModes specified in info.plist. E.g. If application is listening to location events, when location update event is delivered, OS put application in background mode and you can get up to 30 seconds using background task.</li><li>By sending Silent push notification from application server.</li></ul><h3>Conclusion</h3><ul><li>Get up to 30 seconds while application is in background by calling beginBackgroundTask .</li><li>Can have multiple task created associated with each job to be done.</li><li>Even by creating multiple tasks the background time will not exceed 30 seconds.</li><li>A task created should end by calling endBackgroundTask to avoid watch dog killing the application.</li><li>A task should end as soon as the relevant job is done.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d92d0a51dc25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GCD Basics (Serial and Concurrent Queues, Sync vs Async)]]></title>
            <link>https://medium.com/@kkapilchoubisa/gcd-basics-serial-and-concurrent-queues-sync-vs-async-fdc3b22bbb3a?source=rss-364968580fc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdc3b22bbb3a</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[sync]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[gcd]]></category>
            <dc:creator><![CDATA[Kapil Choubisa]]></dc:creator>
            <pubDate>Sun, 27 Feb 2022 13:01:44 GMT</pubDate>
            <atom:updated>2022-03-16T05:13:45.391Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s been a long time since I was thinking about writing this. I thought there were a lot of tutorials on GCD out there. However, I came across many iOS developers who can write code, use GCD and accomplish the task, but don’t understand GCD completely.</p><p>In this tutorial, I will try to explain the basics of GCD such as Serial vs Concurrent Queue, Sync vs Async operations etc. So without wasting time, lets get started:</p><h3>What is a GCD Queue?</h3><p>A queue is a data structure, open from both ends, allows you to enter your task from one end and remove it from the other end. GCD Queue guarantees that the task submitted first will be executed first. There are two types of queue behaviour: Serial and Concurrent.</p><p>GCD provides few default queues and we can create custom queues too. DispatchQueue is the GCD class which allows us to access the default queues or create our own.</p><p>DispatchQueue.Main is the serial queue. All the UI operations are performed on this queue. E.g. All your IBActions (cause this are initiated from a UI control), UIGestures, UI Updates, Application and View Lifecycle methods etc.</p><p>DispatchQueue.Global is a default concurrent queue. This is a shared queue for the OS and all the applications on the device will be using this queue.</p><p>You can create your own queue by instantiating DispatchQueue . Check Apple’s class <a href="https://developer.apple.com/documentation/dispatch/dispatchqueue">reference</a>.</p><h3>Serial Queue</h3><p>Consider a queue as a single lane one way road. Once you enter on the road, you can’t make a U-turn and come back because it is one way. And you can’t overtake, no matter how slow the traffic is. The exact same behaviour would apply to the task when added to a GCD queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*VoNHDtC57TutORG9LQBD7Q.png" /><figcaption>Serial Queue (one-way road)</figcaption></figure><p>Whenever you add any task in the queue, whether synchronously or asynchronously, it will be added at the end of the queue and will be executed once all the tasks in the queue before are completed.</p><h3>Concurrent Queue</h3><p>Similar to the serial queue, it is still a one way road, but it is now having multiple lanes. GCD will be able to process multiple tasks at once and will be picked based on the QoS level. QoS level is the priority of the queue in simple words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*wfrjZNbaARfQcc1FGEBIPw.png" /><figcaption>Concurrent Queue</figcaption></figure><p>Since we understand the serial and concurrent queues now, let’s understand the types of operation on each type of queue. Before that, let’s recall few key points of a queue:</p><ul><li>Every time a task is dispatched, there is a source and target queue.</li><li>Source queue is the queue from where the Dispatch is called.</li><li>Target is the queue on which the code is dispatched.</li><li>Tasks are appended at the end of the queue.</li><li>Task will be appended on the target queue on which it is dispatched.</li><li>Source queue’s length will not have any impact on the execution of the task.</li><li>The task from where we have dispatched a new task will have an impact based on the dispatched operation type (sync or async)</li></ul><p>Note: A ’task’ refers to the closure/block of code you provide in the dispatch section.</p><h3>Sync Operation</h3><p>When a task is dispatched using sync operation, the impact is on source task. What it means is that the execution after the line of code from where you have dispatched will wait till the dispatched block is completed. E.g.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfb7f78c506a0b40983c795896b7283f/href">https://medium.com/media/bfb7f78c506a0b40983c795896b7283f/href</a></iframe><p>Let’s break the code into pieces to learn it</p><ul><li>The function performSyncOperation is IBAction. So, it will execute on main queue.</li><li>Source of dispatch task is line #3 of the above code.</li><li>It doesn’t matter that source queue is serial in the operations. So we are least bothered about it.</li><li>Target queue is global queue.</li><li>sync operation makes sure that the code execution in the source queue will wait till the target queue completes the task.</li></ul><p>With above points, when this block of code gets executed</p><ul><li>It will first execute line #2.</li><li>Then dispatch task on global queue using a sync operation. This means that source will wait here.</li><li>Global queue will execute the task based on its priority.</li><li>Once global queue completes the task, source will execute next line i.e. #6</li><li>So output will be print statement 1 , print statement 2 and print statement 3</li></ul><h4>Sync operation on serial queues</h4><p>We should take caution while working with serial queues and using sync operations. As you know now, that sync operation, keeps your source in waiting state. This means that the source task is not leaving the queue until the dispatch sync operation is completed. If the source queue is serial and you directly or indirectly dispatch something on the source queue again, it’s going to be deadlock. See the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e3fd5e6f65021c5782c2f5067fff5ed/href">https://medium.com/media/1e3fd5e6f65021c5782c2f5067fff5ed/href</a></iframe><p>Similar to the previous example, here as well, this is IBAction hence</p><ul><li>Source is main queue. It will execute line #2 and print the statement. Then it will go on to line #3.</li><li>This method will wait for the block on line #3 to get completed before it takes #6.</li><li>Since line #3 is a dispatch on main queue, it will get added in main queue.</li><li>Main queue being serial, will wait for current task (the method) to complete before taking the task dispatched on #3.</li><li>The method is not completing it’s task because it is waiting for the task on #3 to complete first because of sync operation.</li><li>…and it is deadlock.</li></ul><h4>Sync Operation on Concurrent Queues</h4><p>These types of operations are safer until a serial queue is involved. Because concurrent queues can execute multiple tasks at a time. So even if you use dispatch sync on (same or different) concurrent queues, it doesn’t create the deadlock and block the code execution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f595b26cba06848eff09e971f33944df/href">https://medium.com/media/f595b26cba06848eff09e971f33944df/href</a></iframe><ul><li>On line #2, main queue will wait because the method is executing on main queue.</li><li>The target queue is global which is concurrent queue.</li><li>It will print #3 and dispatch another task on the same queue on #4.</li><li>Global queue, being a concurrent one, able to process multiple task. Hence one process of it is waiting on #4, other process is executing the task and print #5</li><li>Once the inner task is done, wait for the process on #4 is over and that will execute #6.</li></ul><h3>Async Operations</h3><p>Async operations are simple. It simply add the task at the end of the queue and allows current task to continue without waiting. Since it only adds the dispatched task to the end of the queue, the type of target queue doesn’t have any impact on how the code is executed in the source queue. It is perfectly fine to use the same queue and it won’t create a deadlock.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/981420f26eb7fe95efd613a09dce7525/href">https://medium.com/media/981420f26eb7fe95efd613a09dce7525/href</a></iframe><h3>Conclusion</h3><ul><li>Serial queues execute tasks one by one.</li><li>Concurrent queues will initiate multiple processes and allows multiple tasks to be run in parallel.</li><li>Sync Operation keeps the source in waiting mode.</li><li>If source is serial and if directly or indirectly, the dispatch sync comes back to the source, it can create dead lock.</li><li>Use sync operation wisely and only where it is needed. Use it only if you want to hold current execution and wait until the new task is not completed.</li><li>Async operation simply append task at the end of target queue.</li></ul><h3>What next?</h3><p>I will come back soon with Dispatch Groups, Dispatch Work Items, custom queues and QoS levels.</p><p>Check your knowledge by answering the output of below two exercises in comments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a12b4198431f61b37e8199efde77ced5/href">https://medium.com/media/a12b4198431f61b37e8199efde77ced5/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdc3b22bbb3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>