<?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 Arya Surya on Medium]]></title>
        <description><![CDATA[Stories by Arya Surya on Medium]]></description>
        <link>https://medium.com/@aryasurya?source=rss-7b2dd20adf43------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z-wHYg0Jo-iLewI05T2FPA.png</url>
            <title>Stories by Arya Surya on Medium</title>
            <link>https://medium.com/@aryasurya?source=rss-7b2dd20adf43------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:01:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aryasurya/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[Dealing with string matching gracefully]]></title>
            <link>https://aryasurya.medium.com/dealing-with-string-matching-gracefully-fb7caea0ef6b?source=rss-7b2dd20adf43------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb7caea0ef6b</guid>
            <category><![CDATA[aho-corasick]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[string-matching]]></category>
            <dc:creator><![CDATA[Arya Surya]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 12:37:19 GMT</pubDate>
            <atom:updated>2024-01-13T12:37:19.174Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IxCnPFhYT5GPpcPi.png" /></figure><h3>Aho-Corasick</h3><p>It is a word that I remember vividly since the university time. The first time I noticed, it was written in one of the lecturer’s slides. This name intrigued me not only because of its unusual name, but also what it had to do with computer science. Since then, I tried to find out what it actually does and turns out it is an algorithm that combine the ideas in <a href="https://www.ics.uci.edu/~eppstein/161/960227.html/">KMP algorithm</a> with those of finite state machines.</p><h4>“Sigh, another string matching algoritm” ━━ my thought at that time</h4><p>Since I found string matching was very hard to understand, I don’t bother not to put myself into more confusion by learning this, at least I know what it is used for, my naive thought at that time.</p><p>Long story short, in my latest job, I am required to perform an efficient string matching in an all-limited environment. This might provoke some of you to think why an iOS engineer had to put all the hardwork in the client side? this is due to the current circumstances and constraints that we had, that, we don’t have any better choices at the moment.</p><p>The job might seemed very intimidating at the moment, and to make things even worse, the constraints given were quite high, which means naive solution is not guaranteed to be working all the time, I had to come up with something better.</p><p>This is when I thought of the Aho-Corasick. After researching and reading the <a href="http://cr.yp.to/bib/1975/aho.pdf">original paper</a>. I was amazed of how Alfred V. Aho and Margaret J. Corasick’s intuition works for them to be able to deduct the string matching process into such a beautiful, mathematically proven and efficient process. The algorithm is able to find any words form a finite set of dictionary that is also a substring in a given string in a linear time.</p><p>In short, this algorithm utilizes a trie where each node have this property</p><ul><li>Symbolizes a character</li><li>Has a reference to another node which have the longest suffix of the node’s character, this reference is often called failure transitions or failure links.</li><li>If the node is leaf node, it stores an array of the the current word.</li></ul><blockquote><em>This failure transitions enable the algorithm to perform the a linear time search, that is, if the current character is not matching, we can follow the failure link to start matching again from the failure node, this way, we do not retry the search from the node and save a lot of time.</em></blockquote><p>The matching process is described as we traverse the trie simply like an automaton, If yes, continue, otherwise follow the failure node. and along the node visit we collect the stored word in a node if it exists.</p><h3>How’s the Performance?</h3><p>Performance is what we truly care even after we are able to understand how it works. We did some benchmarking on Pixel 4 phone and the result is not dissapointing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JzlO8rf2Wq8fS9oP.png" /></figure><p>Unfortunately I cannot share the code since our version has been modified to support our business need😛, but maybe I can share the pseudocode, which is</p><pre>1. Loop the dictionary of words, constructing prefix trie<br>2. In each node, link the node to its failure node<br>3. When matching, collects the associated words of each node if exists.</pre><p>Until next time👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb7caea0ef6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with iOS App Modularization — An Introduction]]></title>
            <link>https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-an-introduction-e1ee1b3ead6a?source=rss-7b2dd20adf43------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1ee1b3ead6a</guid>
            <category><![CDATA[modularization]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Arya Surya]]></dc:creator>
            <pubDate>Fri, 16 Sep 2022 04:02:45 GMT</pubDate>
            <atom:updated>2022-09-20T03:51:09.382Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started with iOS App Modularization — An Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xba_9rzJQVid_-d4z1j6QQ.jpeg" /></figure><p>This is the first part of the modularization tutorial. Refer to the list below for the complete parts :<br><a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-an-introduction-e1ee1b3ead6a"><strong>Part 1</strong>: Introduction</a> <br><a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-extracting-catalog-83d117ad343e"><strong>Part 2</strong>: Extracting Catalog</a> <br><a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-final-extraction-and-micro-app-29b973a83a39"><strong>Part 3</strong>: Final Extraction and Micro App</a></p><p>App modularization is an issue everyone runs into as a software engineer, moreover, if your app is already grown to the scale that it takes too long to build the entire app, just like the Tokopedia app. In our case, we have to find a way to fasten our build time to meet our weekly release and this is where the modularization helps. By modularizing our app, we can choose to build what we need at the moment thus improving our build time and everyone is happy! <br>Tokopedia uses a custom modularization approach to enable fast development, but before going to custom modularize your app, you have to understand the basics of modularization and all the other related things you need to know, this article will cover all of them and guide you to have your first taste of modularization, hang tight!</p><p>There is a slew of solutions you can use to tackle modularization. From splitting codebase chunks to increase maintainability to creating good encapsulation. But what is the motivation behind modularization?</p><p>When should you split your codebase into modularized parts?</p><p>Why should you even do such a thing?</p><h3><strong>What is Modularization</strong></h3><p>Modularization is the practice of dividing features of an application into separated modules so that they are interchangeable, reusable, and easily maintained. If you prefer a less-technical explanation, think of a car stripped off its steer, dashboard, and wheels. All these smaller parts of the vehicle can be fully customized on their own and easily replaced by other parts of the same kind if needed.</p><p>Most teams fall back to the modularization philosophy to split monolith codebases that are too large to handle. It is because as time goes on, the build time grows linearly with the lines of code. Slow build time hurts developers’ productivity in the long run and will result in long waiting times before developers can fully test their apps.</p><p>By splitting the features, developers will only build the needed features without having to compile the entire app. Theoretically, this will decrease the compile time, improving developers&#39; productivity.</p><h3>When Should You Modularize Your App?</h3><p>One question might arise when considering modularization. How do you know if your app needs to be modularized or not?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gbzx5JEm-p4IuF06" /><figcaption>Photo by <a href="https://unsplash.com/@brucemars?utm_source=medium&amp;utm_medium=referral">bruce mars</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The answer to such a question is pretty subjective since it depends on your aims from the start and your current situation. For example, suppose you are building a startup that needs to have as many features delivered as possible within a tight schedule. In that case, modularizing your app from the very beginning will result in either :</p><p>1. Premature optimization.<br>2. A good foundation while the app is still in its infancy.</p><p>All of these concerns are valid and you must make decisions with this in mind.</p><h3>How to Modularize An iOS App</h3><p>Let’s say your team finally decide it is the best time to perform modularization, and the next question is how to start modularizing your app.<br>Rest assured, you will learn how you can modularize an iOS project step-by-step.</p><p>Consider an illustration below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PU2Ksil7Cka9QAlGXhF51Q.png" /></figure><p>Let’s say you have an iOS app with three features: catalog, product detail, and shared. One way to get the app modularized is to split the app into four different modules, each with a library and a bundle. In iOS, a module is called a framework, and this article will use those two words interchangeably.</p><p>A library is a collection of resources and the code itself, compiled for one or more architectures, in shorter words, it is all the code you have written. Whereas a bundle in iOS is a directory with subdirectories usually used to store assets, files, and many other specific types of content. The framework itself is a group that contains all the libraries and the resources it needed.</p><p>Furthermore, there are two important frameworks that need to be explained :</p><p>1. Main</p><p>Like its name, the main is your main framework; think of it as your app’s entry point.</p><p>2. Shared</p><p>Think of this framework as the place of all components used within the entire app, containing everything like the code of UI components, (e.g accordions, bottom sheet, popup, etc. ). The shared framework is the best place to start splitting the app since it does not depend on anything externally.</p><p>Moreover, iOS has two types of frameworks, dynamic and static, respectively. <br>A dynamic framework is a bundle of code loaded into an executable at runtime instead of compile time. It behaves exactly like a dynamic library, except for the difference that a dynamic framework is a dynamic library embedded in a bundle along with optional assets, such as images. UIKit and the Foundation frameworks belong to this category.</p><p>On the other hand, a static framework is a bundle containing a static library file. They are statically linked, or copied into the executable binary, and not loaded at runtime.</p><blockquote>For the sake of simplicity, this article will only cover extracting a monolith into dynamic frameworks.</blockquote><p>You can read more about dynamic and static libraries here.</p><p><a href="https://pewpewthespells.com/blog/static_and_dynamic_libraries.html">Static and Dynamic Libraries</a></p><h3>Let’s Get Started</h3><p>Clone the starter project here</p><p><a href="https://github.com/tokopedia/ios-modular-tutorial">GitHub - tokopedia/ios-modular-tutorial: Repository for tutorial code base for our medium blog post</a></p><p>Open the MyAwesomeApp.xcodeproj. Try to run the project to get a clue about the app you are trying to modularize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/0*YWjQby-9H8gu2cH9" /></figure><p>As you can see, the app is pretty straightforward, you have a catalog page showing all the product cards and several rows of promotional and inspirational products. Another feature to add is navigating to the respective product detail page upon tapping one of the product cards.</p><h3>1st Step: Convert App Into Xcworkspace</h3><p>The first thing you have to do to modularize our app is to convert our app to an xcworkspace</p><p>Click file &gt; new &gt; workspace, and set the workspace name as MyAwesome. Then, save the .xcworkspace inside the modular folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m71sEi8gYEW5sb0R4WCviQ.png" /></figure><p>Another window will appear and you can close the previous window. Click File, Add Files to MyAwesomeApp, and add your previous myawesome.xcodeproj to your workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdIMzof8xVnPfFw4wCUXfw.png" /></figure><p>Your Xcode will then become something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYoSk4bG5J9JWZWeIGElSQ.png" /></figure><p>Until now, you have successfully added the xcodeproj inside an xcworkspace. Now, you can start to split the features into their own corresponding frameworks.</p><p>Remember that you must start extracting from the least dependable frameworks. By referring to the dependency diagram before, you can see that the least dependable framework is the Shared framework. Start by extracting this framework first.</p><h3>2nd Step: Creating the Shared Framework</h3><p>Create a new framework named Shared and add it to our workspace. Refer to the GIF below for the step-by-step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KJj80lKDIyspno6jWOE5SA.gif" /></figure><p>One thing to note here, remember to choose MyAwesomeApp.xcworkspace the place to add the new framework. On top of that, also make sure the group refers to the MyAwesomeApp.xcworkspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VpjpFRJOw7p6n3IN3A3vQ.png" /></figure><p>Now your workspace will look something like this, with two xcodeproj inside an xcworkspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNn9u2Ytvfg84p2kfC1PzA.png" /></figure><p>The next step is you have to move the all contents of the folder Shared in the MyAwesomeApp framework ( we will call this the main framework in future usages for simpler and better understanding ) to its own Shared framework’s folder. You can use the help of the finder app in order to do so.<br>Right-click on the Shared folder in the main framework, choose Show in Finder , we will call this Shared folder the source folder.<br>Do the same thing for the Shared folder in the Shared framework, and we will call this folder the destination folder.</p><p>Move all the folders inside the source folder to the destination folder, and remember to tick copy items if needed when prompted. You can refer to the GIF below for a better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fqatGYOjKtFZs0hmVyW9Fw.gif" /></figure><p>Next, you have to adjust the module property of the moved asset files. Refer to the UI folder in the Shared framework. Click the custom class section on the right pane of the code editor, click the module text field and type Shared, the framework’s name. Doing so will cause the Inherit module from target checkbox will be automatically unchecked.<br>This step is to set the resource file’s module explicitly to the Shared framework since you have moved the file there, if you do not, the file will still think it belongs to the main framework, since it inherits from the target, causing unexpected behaviours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*07MGue--fzdizIrp8jGcfQ.gif" /></figure><p>Do the same for the InspirationItemCollectionViewCell.xib and InspirationCollectionViewCell.xib .</p><p>The next step is the most essential part of integrating your Shared framework into the main framework.</p><p>Navigate to the main framework, locate the Frameworks, Libraries, and Embedded Content section, and choose the Shared framework to be embedded. This step is to tell the main framework that it has the Shared framework as the dependency when running the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*5GqJeMoS-gKAqSXTJuhbRw.gif" /></figure><p>Try to run the app, but expect the build to fail because of these errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*jbD6haaXpltIjreS7P1fLQ.png" /></figure><h3>3rd Step: Resolving the errors</h3><p>Let’s solve the errors sequentially, navigate to the CatalogPageNetworkProvider.swift</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0CS1_eS7rv0VlAF1FqzJJw.png" /></figure><p>As you can see, most of the errors are caused by the file not having the definition of NetworkResult , this is because the NetworkResult is originally located in the Shared folder, and because you have moved all of the Shared’s contents to its own frameworks, the code from the main framework does not have access to them again.</p><p>The solution for this is you have just to import the Shared framework in the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6260e5399b284bc7c107ea8421a9b4bf/href">https://medium.com/media/6260e5399b284bc7c107ea8421a9b4bf/href</a></iframe><p>But the error persists even if you have imported the framework, this is still happening because apparently the NetworkResult has an internal access control level, any definition that has internal access control level can only be accessed from its own module, and since you are trying to access the enum from outside the framework, you still cannot locate the definition, which explains the error.</p><blockquote>Note that access control level plays a huge role in modularization, you have to determine which code that are exposed and which are not</blockquote><p>Change the access control level to looser access controls, such as public or open. Navigate to the shared framework, find the NetworkResult.swift file and add an access control before the enum definition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c1cadc2fac9f48a7b2d4c20fbc19a97/href">https://medium.com/media/1c1cadc2fac9f48a7b2d4c20fbc19a97/href</a></iframe><p>The errors in CatalogPageNetworkProvider.swift should be solved now.</p><p>Navigate to the ProductDetailPageViewController.swift . The errors are because the file cannot find the definition of the Product struct and the load function since those definitions are already moved into the shared framework, hence the solution is the same as the previous errors, which is<br>1. Adjust access control levels<br>2. Import Shared</p><p>Import the shared framework at the top of ProductDetailPageViewController and add a public control level in front of the load function definition in UIImageView+Extension.swift . You should have resolved the errors.</p><p>Next up, navigate to the CatalogPageViewModel.swift , the same errors are happening in this file, it cannot identify the HashDiffable protocol and the ProductResult .<br>You can use a similar solution, import the shared framework on the file and add a public access control to the HashDiffable definition and its isEqual function.</p><p>Lastly, the CatalogPageViewController , where it cannot identify the Product struct. Simply importing the shared framework in this file will solve the error.</p><p>Try building the app and it should have been able to run now.</p><h3>4th Step: Handling Bundle Issues</h3><p>One thing that you will notice upon the app launch is your app does not look like it used to be before modularization, you have only presented a white screen and your list of product cards is gone. Why is this happening?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F6HNonYwCD4yrHFk7ya%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fjoebuddennetwork-thinking-think-rory-6HNonYwCD4yrHFk7ya&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2F6HNonYwCD4yrHFk7ya%2Fgiphy.gif%3Fcid%3D790b76119c595ee6b4721da6473852565f5847b99027131e%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3dc63a8ea67ded873562424ac3f5beb/href">https://medium.com/media/a3dc63a8ea67ded873562424ac3f5beb/href</a></iframe><p>Luckily, looking at the app console, you should see the error’s root. A message : URL NOT FOUND.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hum5JQApwH8PJhA-nYeqmw.png" /></figure><p>If you try to find the error string in the entire app, you will notice that it is only coded in the CatalogPageNetworkProvider.swift . Furthermore, If you look further into the code, the errors are because you can&#39;t locate the ProductData.json</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb9864dbaee6109d97c25992a94a531c/href">https://medium.com/media/cb9864dbaee6109d97c25992a94a531c/href</a></iframe><p>This happens because the ProductData.json is already moved to the Shared framework, but how can you access the file using a bundle? 🤔</p><p>First, to access a bundle from a framework, you have to know its identifier.</p><p>Navigate to the Shared framework, click on the target and inspect the general tab. Turns out you already have a bundle identifier of the shared framework, and you can use this in order to access the files within the framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UUSjALKfjyNCi4vyKjp0w.png" /></figure><p>Navigate back to the CatalogPageNetworkProvider.swift , change the guard validation in both of the fetchProductand fetchInspiration</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0d7573eb2ef43dc310c7d197905ccd6/href">https://medium.com/media/b0d7573eb2ef43dc310c7d197905ccd6/href</a></iframe><p>Instead of using Bundle.main , use your shared framework’s bundle by initializing it using the bundle ID. Remember to update the bundle ID to your framework’s bundle ID as your organization name most likely will be different.</p><p>Try to run again the app. This time, instead of getting the error message URL NOT FOUND, your app will crash.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FDyvyiFFXF1Yli%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fdesusandmero-funny-lol-DyvyiFFXF1Yli&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcGZydm5jM2x3bGN6ZXk2YTFyZWhpMnRqcXhmOTF6dHdwcWx1azY5bSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FDyvyiFFXF1Yli%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/83f115be1221e5dd73c836b7ffe32afb/href">https://medium.com/media/83f115be1221e5dd73c836b7ffe32afb/href</a></iframe><p>Suppose you try to debug further from the stack trace, you will see that the crash is caused by CatalogPageViewController calling the cellForIndexPath function, which triggers the collectionView to load the ProductCollectionViewCell, but it was unable to do so, causing the crash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LD4NpSy6bwEPIMHfHNERtg.png" /></figure><blockquote>On the brighter side, this crash proves you have successfully loaded the JSON files since it is happening on the CatalogPageViewController ‘s function that is triggered upon receiving data.</blockquote><p>Your view controller causes the error since it cannot identify the ProductCollectionViewCell . The solution is to specify the bundle where this view controller loads the NIB.</p><p>Locate the viewDidLoad function inside the CatalogPageViewController , and change the code to become :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee1045a370695ca93d97c7b5819eadff/href">https://medium.com/media/ee1045a370695ca93d97c7b5819eadff/href</a></iframe><p>Try running the app, and you will get another crash caused by the same issue, the InspirationCollectionViewCell could not load its NIB. Locate its awakeFromNIB function and change it into this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec49fd17281a3b3379526d6e33cfedca/href">https://medium.com/media/ec49fd17281a3b3379526d6e33cfedca/href</a></iframe><blockquote>Remember to adjust the identifier to your own bundle ID</blockquote><p>After changing the code, try to rebuild the app and it should run successfully!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*2Fx8uf4jlnLpjTJ0anyRVA.gif" /></figure><p>You have successfully extracted your shared module, leaving only two more features before you finish modularizing your app. We will continue extracting the catalog feature into its framework next.</p><p>You can access the code materials until this point here.</p><p><a href="https://github.com/tokopedia/ios-modular-tutorial/tree/feature/extract_shared">GitHub - tokopedia/ios-modular-tutorial at feature/extract_shared</a></p><p>Now let’s continue to the second part <a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-extracting-catalog-83d117ad343e">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1ee1b3ead6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-an-introduction-e1ee1b3ead6a">Getting Started with iOS App Modularization — An Introduction</a> was originally published in <a href="https://medium.com/tokopedia-engineering">Tokopedia Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with iOS App Modularization — Extracting Catalog]]></title>
            <link>https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-extracting-catalog-83d117ad343e?source=rss-7b2dd20adf43------2</link>
            <guid isPermaLink="false">https://medium.com/p/83d117ad343e</guid>
            <category><![CDATA[modularization]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Arya Surya]]></dc:creator>
            <pubDate>Fri, 16 Sep 2022 03:56:13 GMT</pubDate>
            <atom:updated>2022-09-20T03:52:06.254Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started with iOS App Modularization — Extracting Catalog</h3><p>This is the second part of the modularization tutorial. Refer to the list below for the complete parts :<br><a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-an-introduction-e1ee1b3ead6a"><strong>Part 1</strong>: Introduction</a> <br><a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-extracting-catalog-83d117ad343e"><strong>Part 2</strong>: Extracting Catalog</a> <br><a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-final-extraction-and-micro-app-29b973a83a39"><strong>Part 3</strong>: Final Extraction and Micro App</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xba_9rzJQVid_-d4z1j6QQ.jpeg" /></figure><p>In this article, you will continue to extract the catalog feature.</p><p>Refer to the link below for the starting project template, or you can continue with your existing project if you come from the first part of the article.</p><p><a href="https://github.com/tokopedia/ios-modular-tutorial/tree/feature/extract_shared">GitHub - tokopedia/ios-modular-tutorial at feature/extract_shared</a></p><h3>1st Step : Creating The Catalog Framework</h3><p>We will start this article by creating a new framework named Catalog. Choose File &gt; New Project, choose Framework and remember to add it to your xcworkspace . Refer to the GIF below for a better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*EtN7Xvpg4ScZXcNhkBgpwA.gif" /></figure><p>The next step is to move all the Catalog’s folder contents in the main framework into its framework now, refer to another GIF below for clarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_-M9jvkVrvr2JDfT_EmL0A.gif" /></figure><p>The first thing to do upon framework creation is to add the framework’s dependency. In this case, you have to add the Shared framework as a dependency since Catalog relies on it heavily for the models and other assets. Click on the Catalog project, find the targets tab and scroll until the Framework, Libraries, and Embededded Content section. Click the plus icon and choose the Shared framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*a0V6-3V7mXO-rSj1ykxaOw.gif" /></figure><p>The next step is to set asset files in the new Catalog framework to point to its module, click the CatalogPageViewController.xib . Locate the File Owner option on the Placeholders section, then choose the custom class tab, and type Catalog at the Module text field, and the Inherit module from target will be automatically unchecked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9UP1REtzaXYN_j47kmefg.png" /></figure><p>Try to run the app but expect the build to be failed because of the ACL and import-related issues.<br>One place that errored first is SceneDelegate.swift located in the main framework. Simply importing Catalog will resolve the issue, but before that, you have to add the Catalog framework as the main framework’s dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6gZXpDbIO6GjHHa5fDGqQQ.gif" /></figure><p>Try to rebuild the app again, but the error will persist. This is caused by ACL since the CatalogPageViewController ‘s access control is internal. Add a public access control before the class definition and make all its exposed functions public, the resulting code will be like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79d4b663b1a1fca2869019571d0e9473/href">https://medium.com/media/79d4b663b1a1fca2869019571d0e9473/href</a></iframe><p>Even after all these ACL modifications, our catalog feature still will not build because the file cannot identify the ProductDetailPageViewController .<br>One might argue that the solution to this is just to<br>1. Extract the product detail into its framework<br>2. Simply import the product detail module at our catalog framework</p><blockquote>This approach will work but it will cause a dependency issue if later, the product detail page needs to use classes/models from the Catalog framework, you will end up having a circular dependency in your app.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FpoOsWEQNzdORIiJ8NH%2Fvideo&amp;display_name=GIPHY&amp;url=https%3A%2F%2Fgiphy.com%2Fclips%2Fjustin-reaction-meme-realization-poOsWEQNzdORIiJ8NH&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2FpoOsWEQNzdORIiJ8NH%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="480" height="332" frameborder="0" scrolling="no"><a href="https://medium.com/media/662004c0b2e00b1863a7b9e5a32e3c04/href">https://medium.com/media/662004c0b2e00b1863a7b9e5a32e3c04/href</a></iframe><h3>2nd Step : Designing The App Router</h3><p>A better solution to the previous one mentioned before is you can create an abstraction that acts as a route handler in the Shared framework, then when any features that want to navigate to another module can just use the abstraction without having to be tightly coupled to the destination framework.</p><p>Navigate to the Helper folder inside the Shared framework and add a new file named Router.swift</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b36c980cbc472e7b707bd927900139a/href">https://medium.com/media/4b36c980cbc472e7b707bd927900139a/href</a></iframe><p>This will be a blueprint for our navigation capability. Now, head back to the CatalogPageViewController and replace the didSelectItemAt indexPath function extension to become like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2f72470435bbcf438b6ff5b38dd6483/href">https://medium.com/media/f2f72470435bbcf438b6ff5b38dd6483/href</a></iframe><p>Try to run the app. Now, it will be successfully built but crashed as soon as it runs. The crash is caused by the CatalogPageViewController since it cannot find its XIB.<br>Navigate to CatalogPageViewController , locate its init function and change them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b9ceb7154b7fc695c7fab6e1f3e3178/href">https://medium.com/media/6b9ceb7154b7fc695c7fab6e1f3e3178/href</a></iframe><blockquote>Bundle(for: Self.self) is used to refer the bundle within the module itself, you can use this directly instead of Bundle(identifier:) since the CatalogPageViewController.xib lives inside its own framework.</blockquote><p>Try to rebuild the app again, and this time the app will successfully run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*qFap6rN4ivU_RPNMY6t0SA.gif" /></figure><p>But one capability is missing from our app, if you try to click one of the product cards, it will do nothing instead of navigating to the respective product detail page, why is this happening?</p><p>Remember atCatalogPageViewController , you have changed the didSelectItemAt indexPath function definition to use Router instead of manually navigating. The navigation will not work yet because you have not created the definition for the route function, which explains the bug.</p><p>Navigate SceneDelegate.swift inside the main framework. Add the route definition at the very end of the scene function :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/817b9366a0b53936a49d9c15742968a8/href">https://medium.com/media/817b9366a0b53936a49d9c15742968a8/href</a></iframe><p>By doing this, the app will be able to perform navigation from any modules without ending up having a circular dependency or becoming tightly coupled with unnecessary modules.<br>Try to run the app, and the navigation will now work smoothly.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F62PP2yEIAZF6g%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F62PP2yEIAZF6g%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F62PP2yEIAZF6g%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="247" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bb5afd9dd418be7b94422bf05dd409d/href">https://medium.com/media/8bb5afd9dd418be7b94422bf05dd409d/href</a></iframe><p>Up until this point, you have successfully extracted the Shared and Catalog frameworks, leaving only the Product Detail Page to be extracted.<br>In the next part, you will continue to extract the Product Detail Page into its framework and learn how to build one single framework instead of the entire app.</p><p>Now, let’s continue to the final part <a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-final-extraction-and-micro-app-29b973a83a39">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83d117ad343e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-extracting-catalog-83d117ad343e">Getting Started with iOS App Modularization — Extracting Catalog</a> was originally published in <a href="https://medium.com/tokopedia-engineering">Tokopedia Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with iOS App Modularization — Final Extraction and Micro App]]></title>
            <link>https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-final-extraction-and-micro-app-29b973a83a39?source=rss-7b2dd20adf43------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b973a83a39</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[modularization]]></category>
            <dc:creator><![CDATA[Arya Surya]]></dc:creator>
            <pubDate>Fri, 16 Sep 2022 03:54:57 GMT</pubDate>
            <atom:updated>2022-09-20T03:52:51.148Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started with iOS App Modularization — Final Extraction and Micro App</h3><p>This is the final part of the modularization tutorial. Refer to the list below for the complete parts :<br><a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-an-introduction-e1ee1b3ead6a"><strong>Part 1</strong>: Introduction</a> <br><a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-extracting-catalog-83d117ad343e"><strong>Part 2</strong>: Extracting Catalog</a> <br><a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-final-extraction-and-micro-app-29b973a83a39"><strong>Part 3</strong>: Final Extraction and Micro App</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xba_9rzJQVid_-d4z1j6QQ.jpeg" /></figure><p>Refer to the link below for the starting project template, or you can continue with your existing project if you come from the second part of the article.</p><p><a href="https://github.com/tokopedia/ios-modular-tutorial/tree/feature/extract_catalog">GitHub - tokopedia/ios-modular-tutorial at feature/extract_catalog</a></p><h3>1st Step : Creating the Product Detail Framework</h3><p>Let’s continue this series to extract the Product Detail feature into its own framework.<br>Create a framework and add it to the existing .xcworkspace</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*TFFPAkaSumbxH9Kjz5J4bQ.gif" /></figure><p>Next up, move all the contents inside the ProductDetailPage folder in the main framework to its own framework, then our project will look at this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gor5HUQo0Bf-68h1nFGqnw.png" /></figure><blockquote>Always remember to add the framework’s dependency first before adjusting the framework’s code.</blockquote><p>Add the Shared framework as the ProductDetail ‘s dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pOzP2H8Al4SqWYYo-n-5LA.gif" /></figure><p>Next, don’t forget to change the ProductDetailPageViewController.xib ‘s module name to ProductDetail .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9aj-o86AZPBDZFSrC1wL8g.png" /></figure><p>After that, try to run the app but always expect it to be failed since you have not adjusted anything yet. If you try to inspect the error, it is caused by the file SceneDelegate.swift since it cannot find the definition for ProductDetailPageViewController .</p><p>The solution is to add ProductDetail as the main framework’s dependency, by doing this, the main framework will have access to the ProductDetail framework’s APIs. Refer to the previous GIF to understand how to add a dependency to a framework.</p><p>Next, try to import ProductDetail on the SceneDelegate.swift , the file will become like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ece87df187ef293bd7d3f5afad25ba2a/href">https://medium.com/media/ece87df187ef293bd7d3f5afad25ba2a/href</a></iframe><p>The error still has not been resolved due to ACL issues, navigate to ProductDetailPageViewController and modify the code to the following :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecb14dfd15bb31895ccdaa29ca845d7e/href">https://medium.com/media/ecb14dfd15bb31895ccdaa29ca845d7e/href</a></iframe><p>Try building the app, it will run smoothly with all features working as expected!</p><p>What’s more, you have successfully modularized the monolith app into several modules! 🎊🎊</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSVH9y2LQUVVCRcqD7o%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FSVH9y2LQUVVCRcqD7o%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FSVH9y2LQUVVCRcqD7o%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="324" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e98db6c2b135d5a17ae2d0d59b9886a/href">https://medium.com/media/6e98db6c2b135d5a17ae2d0d59b9886a/href</a></iframe><h3>2nd Step: The Micro App Concept</h3><p>Now you already know how to split an app into several smaller features and achieve modularization, but what if you want to achieve building only necessary features?<br>Let’s say you have to implement some enhancements on the product detail page, theoretically, you only have to build the respective framework without having to compile the entire app. How can you achieve this?</p><p>Here’s where micro apps jump in, what you have to do is just to create a new app target, inside the framework you are working with. This xcodeproj will act like your playground, and developers needed only to compile this feature on development, hence the name micro app.</p><p>Click on the Product Detail framework, find the Targets tab and click the + button underneath the tab. After the choosing window show up, search for app and name it ProductDetailSample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_j-dNH8GCxY4gfgvkbh3Pg.gif" /></figure><blockquote>If your newly generated project files end up being red and can’t be opened like the GIF, quit and reopening the XCode will do the trick.</blockquote><p>Next, add the Product Detailframework as the Product Detail Sample ‘s dependency. This is needed since the sample will only act as a playground for our code in Product Detail , hence you need to import them before you’re able to use them.</p><p>Find the Frameworks, Libraries, and Embedded Content section of the sample’s general tab and add the Product Detail framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09EoAjlkv88gtZxRy5e2TQ.png" /></figure><p>After that, try to run the ProductDetailSample target</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*qIDQ462uztX-y7xEDFvbYA.png" /></figure><p>You will then be presented with an empty screen, which comes from ViewController.swift in the ProductDetailSample folder.</p><blockquote>Try changing the background colour and check whether the screen changes accordingly. :)</blockquote><p>That’s it. You can use the ViewController to embed the ProductDetailPageViewController or do whatever you want to do with the feature.</p><p>In this tutorial, however, we will try to simply present the ProductDetailPageViewController instead of using the ViewController , to achieve the capability to build only what you need.</p><p>Remove the ViewController.swift and the Main.storyboard .<br>Navigate to ProductDetailSample ‘s general tab and remove the Main from the Main Interface field, and lastly, locate the Info.plist file, expand all the keys from the dictionary until you find a key titledStoryboard Name, and then delete the entry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZRp1mPGtpdUQy2nqNCPcg.png" /><figcaption>Delete the Main inside the text field and press enter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVxHONI3No0hzs2tiN4l5g.png" /><figcaption>Delete the highlighted entry by simply pressing delete</figcaption></figure><p>Finally, navigate to SceneDelegate.swift , change the code inside the scene function to become :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd087b51fd0e97cfad274f43758e02bf/href">https://medium.com/media/cd087b51fd0e97cfad274f43758e02bf/href</a></iframe><p>Try to run the app again, then it will show only the product detail page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*w2IWlioQ3GROjQku2tjjzg.png" /></figure><p>Now, if you want to enhance the product detail page, for example by adding an image carousel, product description, or anything else, you can code them and directly build this ProductDetailSample to speed up your development.</p><p>Congratulations! 🎉🎉<br>You have modularized the app and even provided a minor app in one of your features!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o6nUOsQeBtw6DRYDm%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o6nUOsQeBtw6DRYDm%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3o6nUOsQeBtw6DRYDm%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="168" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a90b0cf18da7df27d12646a97f045f0/href">https://medium.com/media/7a90b0cf18da7df27d12646a97f045f0/href</a></iframe><blockquote>you can also go the extra mile to create a minor app for Catalog and Shared framework as well. :)</blockquote><p>The final code of the project can be found at :</p><p><a href="https://github.com/tokopedia/ios-modular-tutorial/tree/feature/micro_app">GitHub - tokopedia/ios-modular-tutorial at feature/micro_app</a></p><h3>Where to Go From Here</h3><p>In this article, you have learnt the definition and some motivations behind modularization, furthermore you have modularized an app yourself and even made a sample app for one of the frameworks, this is just the first step of the modularization journey, there are still so many use cases out there that require us to get help from libraries, or tweak our approach to modularizing. We also have this one story of adopting Bazel in our app to further improve our build time, you can check it here.</p><p><a href="https://medium.com/tokopedia-engineering/how-tokopedia-achieved-1000-faster-ios-build-time-7664b2d8ae5">How Tokopedia Achieved 1000% Faster iOS Build Time</a></p><p>Thanks to <a href="https://medium.com/u/aac7941d4db8">Digital Khrisna</a>, <a href="https://medium.com/u/3aac27ca447">Bondan Eko Prasetyo</a>, <a href="https://medium.com/u/8922102dfc90">Ferico Samuel</a>, and <a href="https://medium.com/u/85accda904b1">Andrey Yoshua</a> for helping to review this series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b973a83a39" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tokopedia-engineering/getting-started-with-ios-app-modularization-final-extraction-and-micro-app-29b973a83a39">Getting Started with iOS App Modularization — Final Extraction and Micro App</a> was originally published in <a href="https://medium.com/tokopedia-engineering">Tokopedia Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to Flutter’s BLoC Architecture]]></title>
            <link>https://medium.com/better-programming/a-comprehensive-guide-to-flutters-bloc-architecture-d2d16022b0b9?source=rss-7b2dd20adf43------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2d16022b0b9</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Arya Surya]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 14:04:44 GMT</pubDate>
            <atom:updated>2022-06-09T14:04:44.810Z</atom:updated>
            <content:encoded><![CDATA[<h4>Is it similar to Redux?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*40JEym29BWfisZVj" /><figcaption>Photo by <a href="https://unsplash.com/@tumbao1949?utm_source=medium&amp;utm_medium=referral">James Wainscoat</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The BLoC architecture has been quite around for some time in the Flutter community, and we can safely say that the community loves it. How the pattern allows us to isolate our logic and make it more testable is just by doing some changes in our app is just pretty awesome stuff.</p><p>In this tutorial, we will learn the BLoC concept and its overall flow by creating a simple app, and by the end of this tutorial, we should already be able to write apps that implement BLoC architecture.</p><blockquote>The BLoC version we’re going to use in this tutorial is 8.0.1 ( the latest version at the time of writing )</blockquote><h3>Some Theories Regarding Bloc</h3><p>There are three core components of the BLoC architecture:</p><ol><li>States<br>States are every condition our page or app might be. For example, if we fetch API from a page, then our page will at least have three states:</li></ol><ul><li>LoadingState<br>In this state, we might want to show a loader on our page so the user understands that we&#39;re trying to fetch some data.</li><li>ErrorFetchDataState<br>In this state, we might want to show an error text, a retry button, or show an alert informing the user something is going wrong with our network call.</li><li>SuccessFetchDataState<br>In this state, we can display a list of cards or data, based on the data we get from the response.</li></ul><ol><li>Events<br>Events are actions that UI sends in order to mutate our page state ( sounds familiar, redux developers? )</li><li>BloC<br>BloC acts as action handlers and state mutators, we can do our business logic here as well, for example fetching APIs, storing shared preferences, etc. Some people call them reducers.</li></ol><p><em>Judging from its concept theories, BLoC is pretty much the same as redux or the composable architecture, so if you happen to understand one of them, you have pretty much understood BLoC.</em></p><h3>Let’s Code</h3><p>Navigate to the code editor of your choice, and create a new Flutter project with any name you may think of. Then, after Flutter finishes creating the boilerplate for us, add flutter_bloc dependency in the pubspec.yaml like such.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/772b3570ec27e13932843b7dea3a897e/href">https://medium.com/media/772b3570ec27e13932843b7dea3a897e/href</a></iframe><p>Replace everything on the main.dart with this code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bbbafc68bcbb42f8686902df8899f65/href">https://medium.com/media/1bbbafc68bcbb42f8686902df8899f65/href</a></iframe><p>In the code above, we create a home screen widget with a button in the centre of the page. Pretty straightforward.</p><p>What we are going to do next is we are going to add several functionalities to our app, our final app could display a list of food cards or an error message depending on the response we get from our API.</p><p><em>For the sake of simplicity, we are not going to hit any real endpoints, we’re going to just random the result every time the user pressed the button.</em></p><p>Create a new file named food.dart, this file will contain the model for our food card.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32e570b5df436d724a6e8a21f1cf2c7e/href">https://medium.com/media/32e570b5df436d724a6e8a21f1cf2c7e/href</a></iframe><p>Create another new file named food_generator.dart, this file will provide us with all of the dummy data displayed on the app. Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d23dba52cc271d87fc4c70bcb805a1b2/href">https://medium.com/media/d23dba52cc271d87fc4c70bcb805a1b2/href</a></iframe><p>Next, let’s proceed to our first BLoC-related code, here we are going to create the classes for our state and events.</p><p>Create a new file named home_state.dart and add the following code inside the file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed8164d0082a3182a5a30d2e242d5dca/href">https://medium.com/media/ed8164d0082a3182a5a30d2e242d5dca/href</a></iframe><p>From the requirements, our app can only do one thing at the moment, which is trying to fetch data when the button is pressed. From there, we can imagine that our page should at least have three states:</p><ol><li>HomeLoadingState<br>This is the state when we’re waiting for the API response, we might want to show some kind of loader indicator or shimmer to let the user know that it’s still processing.</li><li>HomeErrorFetchDataState<br>This is when we receive an error from the API, and we might want to show an alert or display some error widgets.</li><li>HomeSuccessFetchDataState<br>This is when we successfully receive our food data from the API, we might want to show a list of food cards here.</li></ol><p>Besides the three states mentioned above, we also have to create another HomeInitialState. This is the first state of the page since we did not want to show the loader when a user views the page. More on this below.</p><p>Next, we should define the actions that the page can send, you can imagine actions are anything that triggers state changes. Create a new file named home_event.dartand add this code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a208637ad280efd913ead0d23f0e42ca/href">https://medium.com/media/a208637ad280efd913ead0d23f0e42ca/href</a></iframe><p>Since our home page can only do one thing at the moment, fetch data, we have to create this fetch data event as one of our HomeEvents. Remember sending events is how our widget tells the BLoC that they want to do something.</p><p>So, for example, if you want to hit trackers when we view the page, you can add another event here.</p><p>Finally, we have to create a BloC class, this class acts as an action handler that does all the business logic and gives the result back to our page through its state construction. Create a new file called home_bloc.dart and add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87241390f0248859a985ff123cd42ec4/href">https://medium.com/media/87241390f0248859a985ff123cd42ec4/href</a></iframe><p>Our HomeBloc extends the base Bloc class which expects two parameters: our event and state classes. This is to tell the Bloc that we are dealing with events and states of type HomeEvent and HomeState respectively, which answers the question of why we create them as abstract classes.</p><p>Inside the constructor, we should provide the class with our initial state via its super constructor. Since we are not doing anything when viewing the page for the first time, we can just make another empty state, in this case, the HomeInitialState.</p><p><em>But if, for example, you want to directly show shimmer when user opens the page, you might consider setting </em><em>HomeLoadingState as its initial state in the constructor.</em></p><p>Inside the super constructor closure, we have to list down all the events that might be sent to our HomeBloc, and since we only have one action, we only put one. Or if you prefer a more friendly explanation, line 6 can be understood as follows:</p><p><em>When the HomeBloc receives a </em><em>FetchDataEvent, it will try to handle the event by executing the handler given to it, in this case, the </em><em>_onFetchDataEvent function.</em></p><p>Now, what do we do inside the _onFetchDataEvent?</p><p>Remember that we want to fetch data and return the response to our home page. In this case, I will just delay the function execution for two seconds to simulate network calls and generate a random boolean to determine whether we got a list of food or an error.</p><p>And while processing all those logic, we want to show a loader on our page, so the algorithm will be like this:</p><ol><li>change state to HomeLoadingState</li><li>delay the function execution for two seconds to simulate network call</li><li>random a boolean, if it is true, we change state to HomeSuccessFetchDataState, bringing a list of dummy food, otherwise, we change the state to HomeErrorFetchDataState.</li></ol><p>Add some changes to the _onFetchDataEvent<em> </em>function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd925f88d166d7a55aaec30c5c9a7762/href">https://medium.com/media/dd925f88d166d7a55aaec30c5c9a7762/href</a></iframe><p>Congratulations! We have just finished our BLoC code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FPh05xuYgrX5te%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fthumbs-up-zach-galifianakis-the-hangover-Ph05xuYgrX5te&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2FPh05xuYgrX5te%2Fgiphy.gif%3Fcid%3D790b7611da82dddeda290242607b34bd2e4bd5e1cd91bc5b%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="174" frameborder="0" scrolling="no"><a href="https://medium.com/media/683c07ffa9e5c815e4b6fa5f56a1e3a7/href">https://medium.com/media/683c07ffa9e5c815e4b6fa5f56a1e3a7/href</a></iframe><p>One final thing to do is modify our widget (home screen) so that it can listen to the state mutations happening inside the BLoC. With this done, we can change our UI accordingly to our state (e.g., showing some try again button when an error happened, etc.).</p><p>Fortunately, the BLoC library has us covered. All we have to do is wrap our widget in a BlocConsumer widget and we’re ready to go!</p><p>Navigate to main.dart and change the code to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49d20de4d52e5eeb66e6a1e545621958/href">https://medium.com/media/49d20de4d52e5eeb66e6a1e545621958/href</a></iframe><p>BlocConsumer requires us to define two properties, namely listener and builder.</p><p>The builder block of code will be triggered every time the state changes. Therefore, we have to list all the possible states, which is why we can see a lot of if state is ; it is because we have to specifically handle each one of the states.</p><p>The listener block will also be executed when the state changes. The difference between listener and builder is that the builder expects us to return a widget. In other words, what kind of UI you want to show to the user when the state is X, Y, or Z . On the other hand, the listener does not require us to return a widget. This is the place where we do side effects, such as showing alerts, snack bars, hit trackers, etc.</p><p>Add the widgets on each of the states inside the builder, so that our HomeScreen becomes like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eda38ca9d57210c04e9d99b39c947dd6/href">https://medium.com/media/eda38ca9d57210c04e9d99b39c947dd6/href</a></iframe><p>For HomeLoadingState, I just returned a CircularActivityIndicator as the loader for the HomeSuccessFetchDataState, I return a ListView so the user can see all of our foods, and we return an error text with a retry button on the ErrorState.</p><p>Next is, we have to wrap our HomeScreen inside a BlocProvider in the runApp function. This should be done to provide the HomeScreen and all of its children access to the bloc. Otherwise, we will get an error stating the BLoC is not found.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e80b791601234c1fc03a920b07298845/href">https://medium.com/media/e80b791601234c1fc03a920b07298845/href</a></iframe><p>After that, we have to also add the send event capability on our home widget, in order to do so. We have to grab the HomeBloc inside the HomeScreen widget, and because we have already provided them via the BlocProvider , we can read them from the context.</p><p>Add a HomeBloc property and an initState function in the HomeScreen widget like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6338aba1db35b46a17cf0c330971f6b9/href">https://medium.com/media/6338aba1db35b46a17cf0c330971f6b9/href</a></iframe><p>And finally, add the event sending code inside every onPressed function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3331f720d3823fc2977c21bb80966536/href">https://medium.com/media/3331f720d3823fc2977c21bb80966536/href</a></iframe><p>Our final main.dart will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b80d24fedbc48ac910833fb39984941/href">https://medium.com/media/3b80d24fedbc48ac910833fb39984941/href</a></iframe><p>Try to run the app, and voila!, our app should be finished with the requirements fulfilled!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Dm-foUWr3-c9yHy2suNVzw.gif" /></figure><h3>Conclusion</h3><p>BLoC is pretty much the same as redux or the composable architecture, all of them have one instance that acts as an action handler where we do all of the business logic there. And the UI sends state-mutating actions and listens to state changes to perform necessary updates.</p><p>You can find the finished code in my repository here:</p><p><a href="https://github.com/aryasurya21/bloctorial/tree/completed">GitHub - aryasurya21/bloctorial at completed</a></p><p>You can learn more about BLoC at their official documentation here:</p><p><a href="https://bloclibrary.dev/#/flutterbloccoreconcepts">Bloc State Management Library</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2d16022b0b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/a-comprehensive-guide-to-flutters-bloc-architecture-d2d16022b0b9">A Comprehensive Guide to Flutter’s BLoC Architecture</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Progressive Web Apps Guide You’ve Been Looking For]]></title>
            <link>https://medium.com/better-programming/the-progressive-web-apps-guide-youve-been-looking-for-5ae3fa2cea83?source=rss-7b2dd20adf43------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ae3fa2cea83</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Arya Surya]]></dc:creator>
            <pubDate>Wed, 17 Mar 2021 17:41:15 GMT</pubDate>
            <atom:updated>2021-05-07T17:15:17.795Z</atom:updated>
            <content:encoded><![CDATA[<h4>Convert your old boring websites into PWAs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xCfSveaSkmrC8Pfw" /><figcaption>Photo by <a href="https://unsplash.com/@laukev?utm_source=medium&amp;utm_medium=referral">Kévin et Laurianne Langlais</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>PWA, or Progressive Web Apps, is one of the hottest topics in web development these days. It promises users a native-app like experience and features, but still built with common HTML, CSS, and JavaScript (or you can go even further by using any JavaScript frameworks), how cool is that!</p><p><em>This tutorial assumes intermediate level knowledge of HTML, CSS, and JavaScript. If you’re totally new to frontend development, it might not be the best idea to jump right into progressive web apps as your first step — grasp the basics then come back!</em></p><h3><strong>Introduction</strong></h3><p>In this tutorial you will learn how to convert a traditional website into a progressive web app with a lot of cool features.</p><p>But first, let’s jump into some theories. According to <a href="https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps">developer.mozilla.org</a>, progressive web apps are web apps that use emerging web browser APIs and features, along with traditional progressive enhancement strategy, to bring a native app-like user experience to cross-platform web applications.</p><p>In simpler words, progressive web apps are typical web apps, built using the same old HTML, CSS, and JavaScript but with additional capabilities such as offline mode, A2HC (add to home screen), background syncing, push notifications, etc. They look and feel like a native apps but they ain’t!</p><p><em>I guess you could say that progressive web apps are web apps on steroids.</em></p><h3>Coding</h3><p>Now with we already know what PWA is actually, we can start creating a progressive web app right away!</p><p><em>For the of simplicity, I will just cover some of PWA capabilities such as offline mode and A2HC. (Keep in mind that there are still a lot of PWA capabilities besides the ones mentioned above).</em></p><p>I’ve prepared a base project for this tutorial but if you have any websites that you want to convert into a progressive web app, feel free to do so.</p><p><a href="https://github.com/aryasurya21/pwastarter/">aryasurya21/pwastarter</a></p><p><em>Don’t forget to run npm install after you clone the base project.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwPkH3TVuIGUU-GwtHhMgw.png" /><figcaption>Home screen of base project, pardon the gorgeous font.</figcaption></figure><p>The base project itself is a simple website where users can perform CRUD operations on tasks, built using the HTML, CSS, and Vanilla JS we all love so much.</p><p><em>I strongly suggest using Chrome for PWA development since PWA is not supported by many browsers yet.</em></p><p>In order to convert any web apps into a progressive one, there are three main requirements we have to satisfy.</p><h4>1. HTTPS</h4><p>Our web should run on HTTPS connection which means that everything our browser sends and receives from the web server is done with a strong encryption so that third-parties can’t easily eavesdrop on us and/or perform malicious activities.</p><blockquote>Some of you may be asking yourselves, “we’re developing our app on localhost which is based on HTTP Protocol, how can we convert it into PWA locally since it requires HTTPS?” Well, that’s a good question. The answer is simply that even though localhost runs on HTTP, it actually behaves like HTTPS — that’s why some APIs that won’t work on a deployed HTTP site, will work on http://localhost.</blockquote><h4>2. Have app manifest</h4><p>App Manifest is a JSON file that tells the browser about our progressive web app and how it should behave when installed on mobile or desktop. A typical app manifest contains our app’s information such as name, description, icons, and baseURL.</p><h4>3. Have service worker</h4><p>Service Worker is the core of all PWA functionalities. It is a JavaScript file that our browser runs in the background and keep running, even if the browser itself is closed.</p><p>There are a few things to note about service worker:</p><ul><li>It’s a <a href="https://www.html5rocks.com/en/tutorials/workers/basics/">JavaScript Worker</a>, so it can’t access the DOM directly. Instead, a service worker can communicate with the pages it controls by responding to messages sent via the <a href="https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage">postMessage</a> interface, and those pages can manipulate the DOM if needed.</li><li>Service worker uses a lot of promises, since it’s a script that runs in the background. What it mainly does is to listen to events that happen on the browser then provide a callback for each events we interested.</li></ul><h3>App Manifest</h3><p>Let’s start our PWA journey by adding a manifest on our app, add a new file on the public directory named manifest.json<strong>,</strong> then write these JSON and adjust them to your own website properties (if you’re not using the base project).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7265b1674eee3a008cca241492f6a6b/href">https://medium.com/media/d7265b1674eee3a008cca241492f6a6b/href</a></iframe><p>Here is some explanation about the properties:</p><ul><li>start_url<strong> </strong>is the URL of the first page we wanted to show when the website starts. In this project I use “/” where it could automatically find an index.html.</li><li>scope<strong> </strong>is the files on your project that you want to include in your progressive web app. For example, if you only want to include the files inside a src folder inside your project, you could just change it into something like “scope”: “/src”</li><li>display<strong> </strong>is the type of UI you want the app to use, where you can customize what browser UI is shown when your app is launched. For example, you can hide the address bar</li><li>I use<strong> </strong>standalone<strong> </strong>to make the web app look and feel like a standalone app. If you install the app on the desktop, it runs in its own window, separate from the browser, and hides standard browser UI elements like the URL bar.</li><li>orientation<strong> </strong>defines the orientation of the web app.</li><li>dir<strong> </strong>defines the base direction in which to display direction-capable members of the manifest. Together with lang, it helps to correctly display right-to-left languages.</li><li>lang member is a string containing a single <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang">language tag</a>. It specifies the primary language for the values of the manifest&#39;s directionality-capable members, and together with dir<strong> </strong>determines their directionality.</li></ul><p>After we add our own app manifest, what we have to do next is to register it in our HTML file, hence add these line on index.html inside the &lt;head&gt; tag.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f63a45bb34295f2f704fe5690852c5f/href">https://medium.com/media/1f63a45bb34295f2f704fe5690852c5f/href</a></iframe><p>Then our index.html would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa43c662a24c4d862ca9f1322252e8b3/href">https://medium.com/media/aa43c662a24c4d862ca9f1322252e8b3/href</a></iframe><p>After we register the manifest, start the project by running npm start on the project terminal. Then open the developer console, go to the application tab and you will see that the properties we defined on the manifest are now shown on the browser as well!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6Fki4pMgY8cUL94zsWHyw.png" /><figcaption>Manifest Properties</figcaption></figure><p>Congratulations — you are one step closer to convert your app into a progressive web app!</p><h3>Service Worker</h3><p>Next is the most important part of progressive web apps: service worker.</p><p>In the public folder, create a new file called serviceWorker.js, then navigate to index.js. To add a function to register the serviceWorker.js as the web’s service worker, add this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd83611000544a2989e619d1b102074c/href">https://medium.com/media/fd83611000544a2989e619d1b102074c/href</a></iframe><p>Don’t forget to call the function on init(), then our index.js would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e48c8e126da9f5697c9eb5d2f4104750/href">https://medium.com/media/e48c8e126da9f5697c9eb5d2f4104750/href</a></iframe><p>Before we started to code the service worker itself, we have to know about its lifecycle first, which can be detailed as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*rL5BPzlnhwsLdwDF.png" /><figcaption>source : <a href="https://developers.google.com/web/fundamentals/primers/service-workers">https://developers.google.com/web/fundamentals/primers/service-workers</a></figcaption></figure><p>Explanation:</p><ul><li>Installing is the first event a service worker gets after it was registered and it only happens once. This is the best place to cache everything to prepare for offline mode.</li><li>Once our service worker is ready to control clients and handle functional events like push and sync, we’ll get an activated event. This is the best place to clean up caches from old service workers to prevent weird stuff happen when the new service worker is ready.</li><li>Idle means that the service worker is now ready to receive functional events such as push, sync, or fetch. Or we can just terminate the service worker if we don’t need it again or because we’re going to install a new one.</li></ul><p>Based on the explanation above, one question might come to mind :</p><blockquote>How do I know when to update my service worker with a new one?</blockquote><p>The answer is, when something changes in your service worker code, we have to replace the existing one with a new one that reflects the newly added code.</p><p>Next, go to serviceWorker.js. Keep in mind that since service worker is a script that runs in background and cannot access the DOM, all we have to do there is to “listen” to events as stated above.</p><p>Inside serviceWorker.js, let’s listen to install and activate events:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fa20c9db9236eae440e2b9029b4db4f/href">https://medium.com/media/6fa20c9db9236eae440e2b9029b4db4f/href</a></iframe><p>Then, navigate to Chrome, open the application tab, chose“ storage” then “clear site data,” and press CTRL + SHIFT + R to hard reload and force the browser to install a new version of our service worker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aF0Z-HkuL1c7YUBD4om5KA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAfgPIDwOXSgOwJUw5AS8Q.png" /></figure><p>As we can see on the console tab, our service worker is up and running on the browser.</p><p>We ccan see our service worker on the application tab as well.</p><p>Congratulations! We’ve implemented our service worker and app manifest — our app has already satisfied the progressive web apps requirement!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z4Ew5wGuoJJsCfpU" /></figure><p>Now, let’s make our app accessible when the user is offline.</p><h3>Offline Mode</h3><p>Traditional web apps could not be accessed when users are offline, they will only show this dinosaur whenever we try to do so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*WOBK1AdhL3R53OUq3pEnYA.png" /></figure><p>Since progressive web apps are installable on desktop or mobile, whenever users try to use our app when they’re offline they don’t get a good user experience. This dinosaur shows up, hence we have to make our app available in offline mode with the help of an API we have heard about pretty much every day: caching.</p><p>As we learned before, the best time to cache everything we need on the website on the service worker lifecycle is in the “install” phase.</p><p>Hence, add this code on the serviceWorker.js file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/831d8b845bbc82ec9ab61d0920cd7df2/href">https://medium.com/media/831d8b845bbc82ec9ab61d0920cd7df2/href</a></iframe><p>Here’s the explanation:</p><ul><li>I made a STATIC_CACHE_CONTAINER variable which is going to act as the cache’s name.</li><li>Then, I made a STATIC_FILES array that consists of the files I wanted to store in the cache.</li><li>On the install callback, I wrapped the caching process with event.waitUntil to tell the browser not to terminate the service worker until the promise passed to waitUntil is either resolved or rejected.</li><li>Inside waitUntil, I open a cache storage named STATIC_CACHE_CONTAINER (or create it if it does not exist). Then I add all the file paths I wanted to cache into the cache storage.</li></ul><p>Now, go back to Chrome, navigate to the application tab, choose “storage” and “clear site data,” and press CTRL + SHIFT + R to force the browser to install our new service worker. Then when we go to the cache section, we can see the files we added to the cache storage previously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z986s9btwnmaWqI5v8NVbw.png" /></figure><p>But is this enough? The answer is still no. We have cached our files but we have not used the cached version when we’re offline. Next we will listen to the fetch event to help us deal with requests.</p><p>Add the code below to serviceWorker.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e6c55ee4ce5a86de641d4117d6bab24/href">https://medium.com/media/1e6c55ee4ce5a86de641d4117d6bab24/href</a></iframe><p>Explanation:</p><ul><li>I added a fetch event listener inside the service worker.</li><li>Inside the event handling, I wrapped our promise with respondWith(), which prevents the browser&#39;s default fetch handling and allows us to provide a promise for a response.</li><li>For the promise itself, we try to find whether event.request exists in our cache storage. If it exists we just return the cached one in the storage.</li></ul><p>Do a reinstall of the service worker in the browser and voila our page is available offline!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*lK_5nWaXVV7FbnThCdSmDw.gif" /></figure><p>But did you notice anything? Our gorgeous font and all our styling have gone! How can that be?</p><p>It’s because we did not cache — remember on serviceWorker.js, we only cached three files, the index.html, index.css, and index.js. But the font is from Google Font CDN, and the buttons and table styling are from Bootstrap CDN. The solution for this is quite simple: to cache them when the service worker is on its “install” phase.</p><blockquote>I have seen some practices where people divide the caching container into two keys, one for static files and one for dynamic files. Since in this tutorial the website is full of static pages, I won’t go for dynamic caching, but I will add a further reference about them at the end of this tutorial.</blockquote><blockquote>The idea of dynamic caching is to cache every page that the user has already visited, not hardcoding them one by one like in STATIC_FILES.</blockquote><blockquote>However, best practice is to cache the project’s core assets such as fonts, stylings, helper libraries, static pages, and anything that does not change on the website, and leave the remaining page to be stored in dynamic caches.</blockquote><p>Add those styling and font CDN to our STATIC_FILES, hence our serviceWorker.js would be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfd9e02aba6dd364f629609f3cbf44c8/href">https://medium.com/media/dfd9e02aba6dd364f629609f3cbf44c8/href</a></iframe><p>If we try to reinstall the new service worker and go offline, our app would look just as it did when it was online!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*nCJuTZWuGG7Y4Y-qpaSVvw.gif" /></figure><p>Congratulations! You have made your web app available offline!</p><p>Now the only thing we have to do is make it installable and our app is finally going to feel like a native app.</p><h3>A2HC (Add to Home Screen)</h3><p>There are some requirements to make our app installable on both desktop or mobile:</p><ul><li>A web manifest with the <a href="https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Add_to_home_screen#manifest">correct fields filled in</a>.</li><li>The web site to be served from a secure (HTTPS) domain.</li><li>An icon to represent the app on the device.</li><li>A <a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">service worker</a> registered, to allow the app to work offline (this is required only by Chrome for Android currently).</li></ul><p>Surprise, surprise, we’ve already implemented all of them! That means our app is installable!</p><p>Navigate to Chrome and find this icon near the end of the search bar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2pmAd0Cr4PMe05uAn6C5fw.png" /><figcaption>Download Icon</figcaption></figure><p>Click on the icon and it will prompt us to install the web app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*QWISnIuqiXTY8sbgVQJ49A.png" /><figcaption>installation prompt</figcaption></figure><p>Click install and voila! Our app has its own window and is separated from the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rN7lOYmnKxHY91FzxzMrFA.png" /></figure><p>We also got a shortcut to our app on the desktop home screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjqcQAC7IuVAifkLxaXGRg.png" /></figure><p>Finally, we have implemented the A2HC feature on our web app, making it more feel like a native-app. You could also install the web on your mobile devices by first deploying the website to hosting services such as Netlify, Heroku, or Github pages — the choice is yours!</p><h3>Conclusion</h3><p>We have learned what a progressive web app is and how to convert a traditional web app into a progressive one with some cool features, like offline mode and A2HC.</p><p>Explore more about PWA capabilities here:</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps">https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps</a></li><li><a href="https://developers.google.com/web/updates/2015/12/getting-started-pwa">https://developers.google.com/web/updates/2015/12/getting-started-pwa</a></li><li><a href="https://developers.google.com/web/fundamentals/primers/service-workers">https://developers.google.com/web/fundamentals/primers/service-workers</a></li><li><a href="https://blog.galaxyweblinks.com/how-do-big-companies-build-their-pwas">https://blog.galaxyweblinks.com/how-do-big-companies-build-their-pwas</a>//</li></ul><p>If you have any thoughts and ideas about this tutorial, leave a response below. If you want me to write about any other topics, please leave a message as well.</p><h4>Happy coding!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ae3fa2cea83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/the-progressive-web-apps-guide-youve-been-looking-for-5ae3fa2cea83">The Progressive Web Apps Guide You’ve Been Looking For</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Draggable Floating View in Swift]]></title>
            <link>https://medium.com/better-programming/how-to-create-a-draggable-floating-view-in-swift-13802a410e?source=rss-7b2dd20adf43------2</link>
            <guid isPermaLink="false">https://medium.com/p/13802a410e</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Arya Surya]]></dc:creator>
            <pubDate>Wed, 09 Dec 2020 18:08:34 GMT</pubDate>
            <atom:updated>2020-12-09T18:08:34.111Z</atom:updated>
            <content:encoded><![CDATA[<h4>Add an interesting UI element to your app</h4><figure><img alt="Man swimming underwater" src="https://cdn-images-1.medium.com/max/1024/0*y-JvQj1UM8uDG-QF" /><figcaption>Photo by <a href="https://unsplash.com/@terrawill?utm_source=medium&amp;utm_medium=referral">will terra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>Long story short, on our latest project, our team has to implement a floating view that can be dragged freely on the screen. For those who have an Android development background, think of it as a floating action button lookalike, but instead of staying still on certain parts of the screen, it can be dragged freely!</p><p>For those who don’t, have a look at these images :</p><figure><img alt="Draggable floating view" src="https://cdn-images-1.medium.com/max/869/1*-Wv8kZrHCm63rlOKchESlA.jpeg" /></figure><figure><img alt="Draggable floating view" src="https://cdn-images-1.medium.com/max/869/1*YBAGGFVs4gGRbLymrj3yug.jpeg" /></figure><p>The floating view is circled in red, as shown in the two images above.</p><p>After conducting some research, we found out that it was not that hard to implement it from scratch on an iOS app. This tutorial will cover every single thing you need to create one.</p><p><em>Note: Since I have not found the official name for this component on Apple’s HIG, I will just continue to call it a draggable view in this article.</em></p><h3>Preparation</h3><p>Create an iOS project on Xcode, choose storyboard as the project’s interface and UIKit App Delegate as its life cycle. Then we end up with the usual Xcode starter code that you love so much:</p><figure><img alt="Preparing the project" src="https://cdn-images-1.medium.com/max/1024/1*0sEGYPyC_Gp0EmQ1qBgn7g.png" /></figure><p>Then, go to Main.storyboard, add a UIView, and place it somewhere on the screen. You are free to decide where to put the view. For example, mine would be:</p><figure><img alt="Placing the UIView" src="https://cdn-images-1.medium.com/max/1024/1*yk9HfN0HbgwsMYJFJUDj6Q.png" /><figcaption>I made a red UIView with a 70pt width and height, aligning its trailing to a safe area by 16pt constraint and 300pt to the safe area’s bottom.</figcaption></figure><p>For simplicity’s sake, our draggable view will just be a circular view with some background colour on it. You could always go further by customizing it (e.g. by adding an image or something else).</p><p>What we have to do next is to connect our newly made view to the ViewController:</p><figure><img alt="Connecting view to ViewController" src="https://cdn-images-1.medium.com/max/1024/1*a0kZ36rfx9kuDGP77Jp6Ag.png" /></figure><p>If we run our application right now, we will see a little red box on the screen.</p><h3>Let’s Get Started</h3><p>In order to make our view draggable, we have to add a gesture recognizer called UIPanGestureRecognizer.</p><p><a href="https://developer.apple.com/documentation/uikit/uipangesturerecognizer#//apple_ref/occ/cl/UIPanGestureRecognizer">Apple’s explanation</a> of UIPanGestureRecognizer is quite straightforward:</p><blockquote>“A discrete gesture recognizer that interprets panning gestures.</blockquote><blockquote>…</blockquote><blockquote>Clients of this class can, in their action methods, query the UIPanGestureRecognizer object for the current translation of the gesture (translation(in:)) and the velocity of the translation (velocity(in:)).”</blockquote><p>In simpler terms, this gesture can detect any translation that happens on the view, even enabling you to acquire its attributes such as velocity, final location, etc.</p><p>Let’s try to implement it on our ViewController:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb7cb29b5964a3ec968d788a4cf1e776/href">https://medium.com/media/eb7cb29b5964a3ec968d788a4cf1e776/href</a></iframe><p>Here’s the play-by-play :</p><ol><li>On line 16, we set a UIPanGestureRecognizer to our draggable view, where we also made a callback function for our recognizer (which is called every time the panning event is emitted).</li><li>On the handler function, we simply print the gesture’s current location.</li></ol><p>Try to run the application, then drag the view freely. Notice that although our view is not moving anywhere, we can see some kind of tuple on the debugging console, which is the current gesture location given in a coordinate. We’re on track to achieve our goal!</p><h3>Now What?</h3><p>Now that we have set a gesture recognizer, all we have to do is to update our view’s location. And since we already have our final location from the handler function, let’s just reuse that.</p><p>Add this code to our ViewController:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46bbc36ab8124df8b83817814b10d572/href">https://medium.com/media/46bbc36ab8124df8b83817814b10d572/href</a></iframe><p>In the code above:</p><ol><li>On line 20, we get the gesture’s current location.</li><li>On line 21, we assign the gesture view that sent the panning event (our draggable view) to a variable.</li><li>We then update the view’s center with the current location retrieved before.</li></ol><p>If you try to run the app again, our view is eventually draggable. Yay!</p><figure><img alt="GIF of draggable view" src="https://cdn-images-1.medium.com/max/300/1*sJ7_bgokV1gRbq5pdlPXrg.gif" /><figcaption>Successfully made the view draggable</figcaption></figure><p>But something is not right: Although we successfully made our view draggable, we can drag it beyond the screen, which is not a normal behaviour.</p><p>Besides that, the <em>normal </em>draggable view has the ability to drag itself to the nearest side of the screen when the user stops dragging, while ours does not.</p><p>So what can we do about it?</p><p>Actually, to achieve this behaviour, we only need to do a little workaround. We can apply some logic when the user stops dragging. Add this code to our ViewController:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c66803c13fe2ef7de9927dd7c550c8f/href">https://medium.com/media/0c66803c13fe2ef7de9927dd7c550c8f/href</a></iframe><p>Here’s the logic :</p><ol><li>Starting on line 24, we add some logic to our handler to make the view have the behaviour we expect.</li><li>We check whether the user has stopped dragging, then we do a comparison between the current view’s midX position and its superview’s width divided by half. We do the comparison to determine whether the current view is closer to its superview’s left or right side.</li><li>If the view’s midX is greater than or equal to half the width of its superview (closer to the right side of the screen), we then update its X position as its superview width minus 40. This means that our view’s final location will be located at 40pt from its superview’s trailing.</li><li>If it is closer to the left screen, we then update its X position to 40. This means that our view’s final location will be located 40pt away from its superview trailing.</li></ol><p>Try to run the app. Voila! Our view now behaves as expected:</p><figure><img alt="GIF of draggable view in action" src="https://cdn-images-1.medium.com/max/600/1*uB4p6xgb_BwlHciNhyObug.gif" /><figcaption>Our draggable view in action</figcaption></figure><h3><strong>Conclusion</strong></h3><p>As you can see, creating a draggable view on iOS is not as hard as it seems. We only need to implement some logic regarding the final position of the view.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13802a410e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-create-a-draggable-floating-view-in-swift-13802a410e">How to Create a Draggable Floating View in Swift</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern : Why You Would Probably Need One]]></title>
            <link>https://medium.com/bina-nusantara-it-division/design-pattern-why-you-would-probably-need-one-2072458fdcea?source=rss-7b2dd20adf43------2</link>
            <guid isPermaLink="false">https://medium.com/p/2072458fdcea</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Arya Surya]]></dc:creator>
            <pubDate>Sat, 24 Oct 2020 07:55:40 GMT</pubDate>
            <atom:updated>2020-10-24T07:55:40.627Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Pattern : Why You Would Probably Need One</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izYbABFgq26PgjTyDhoWtQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@shs521?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Susan Holt Simpson</a> on <a href="https://unsplash.com/s/photos/building-blocks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In the software engineering world, we all aim to build a clean, well-defined and structured application, so that our product is reliable, scalable and easy to maintain. But oftentimes in reality we meet or even unconsciously code an app that is so rigid and fragile that even any minor changes made is going to break our app, admit it that we all at least did this twice in our software engineering journey. 💁</p><blockquote>“What’s the big fuss? I wrote my own code and i knew exactly what to fix if something is broken”</blockquote><p>Some of us may think of the statement above when being challenged on why they write such kind of code, in fact it is true that the one who wrote the code <strong>supposed</strong> to know what is wrong, but mostly in practice, developers work in teams, which means that you work together with other people to build the app, you have to also consider on how your code could impact the app’s readability &amp; maintainability so that any other team member could easily help you when something went wrong, i’m quite sure you don’t want to make the entire team searching for that one particular bug you caused in the massive haystack of the app. 😜</p><blockquote>“Er..Surely no! well then, what can i do about it? How to improve my code quality?”</blockquote><p>Alright then, the very first thing you need is of course <strong>strengthen</strong> your basic knowledge of the language you’re coding with, after that you can use a powerful tool called <strong><em>design pattern</em></strong> to accompany you on your coding journey.</p><h4>WHAT IS DESIGN PATTERN</h4><p>Quoted from <a href="https://sourcemaking.com/design_patterns">SourceMaking</a>, a design pattern is defined as below</p><blockquote>“A general repeatable solution to a commonly occurring problem in software design. A design pattern isn’t a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxTQq5ksO8HGD-iGX8_DOQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@magdalenakulamanchee?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Magdalena Kula Manchee</a> on <a href="https://unsplash.com/s/photos/confused?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>“………Wait..what?”</blockquote><p>In a simpler words, design pattern is a guide, or a concept ( often visualized with diagrams ) that could assist you when code and teach you how to think and build a clear, loosely coupling code.</p><p>You might wonder how design pattern could actually help you just like i stated above, consider this case :</p><p>Let’s say you are an android developer, and for some reason a data analyst on your team require you to add a feature where you have to send user’s history when they use the app in order to study what module do the users visit the most ( in might seem so weird but this thing actually happen in real life ). A normal developer would probably do this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9670aaadbdacbef77e6c2c4f3a24f9b6/href">https://medium.com/media/9670aaadbdacbef77e6c2c4f3a24f9b6/href</a></iframe><p>The developer would create a class and a function to send the log, then somewhere in the code he/she would likely to make an object out of the class and make use of the function created before, just like the code below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53e431eef232b29e8d88b0a64b93da4d/href">https://medium.com/media/53e431eef232b29e8d88b0a64b93da4d/href</a></iframe><blockquote>“The question is, does it work? YES it is working but does it efficient enough? “</blockquote><p>Probably not, because the logging method uses the same class, which in this case the Logger class, if there is 10 menus or modules in the app, then the developer should have at least 10 Logger objects, which is not the best practices ( although it works ) since they are all doing the same thing and surely 10 objects is consuming more space in memory than a single object, then what can we do about it?</p><p>We can do something about it! we can make use of the s<strong><em>ingleton</em></strong> design pattern which suits this problem the most.</p><p>Singleton’s definition on the software engineering world is just the same with those in English, which is a <strong>single entity</strong>. The purpose of singleton, as quoted from <a href="https://sourcemaking.com/design_patterns/singleton">SourceMaking</a> is</p><ul><li>Ensure a class has only one instance, and provide a global point of access to it.</li><li>Encapsulated “just-in-time initialization” or “initialization on first use”.</li></ul><p>The essence of Singleton is just, you can limit the number of object initialization down to a single object and reuse the object all over the code without having to instantiate another one just like the example code above. Seems handy right?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3ohuPifoCpmUJZqq9a%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fspongebob-season-4-spongebob-squarepants-3ohuPifoCpmUJZqq9a&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2F3ohuPifoCpmUJZqq9a%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/8974a5accce9a5ad3f20fbd6a94b40ab/href">https://medium.com/media/8974a5accce9a5ad3f20fbd6a94b40ab/href</a></iframe><p>Let’s see how we can implement it on our code, to make it more effective and neat, consider this code :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc260e15c769dfc5a7862ebb99ea027a/href">https://medium.com/media/cc260e15c769dfc5a7862ebb99ea027a/href</a></iframe><p>We need a little extra effort in our class to make it singleton, here’s the play by play :</p><ol><li>We made a class named Logger</li><li>We then create a companion object of the class. In Kotlin, if you want to write a function or any member of the class that can be called without having the instance of the class then you can write the same as a member of a <strong>companion</strong> object inside the class. So, by declaring the <strong>companion</strong> object, you can access the members of the class by class name only (which is without explicitly creating the instance of the class). You can read more about companion object here ( <a href="https://kotlinlang.org/docs/tutorials/kotlin-for-py/objects-and-companion-objects.html">Companion Object</a> )</li><li>Inside the companion object, we declare an attribute named <strong>instance</strong>, which will be our singleton object</li><li>Starting on line 6, we made a getInstance <strong>getter</strong>, where it would return an instance of our Logger class, but firstly it checked whether our <strong>instance </strong>attribute is already instantiated or not, if it is null ( have not been instantiated ), then the <strong>instance</strong> get assigned a new object of our Logger class module, the assignment will only happen on the first time the getter is called, because the next time the getter is called, it will just return the already instantiated object before.</li></ol><p>We then could call our singleton class like such</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80c80f0048cc64a1cabdfad58a82da46/href">https://medium.com/media/80c80f0048cc64a1cabdfad58a82da46/href</a></iframe><p>And voila 🎊🎊, our first design pattern implementation!</p><p>Notice on the code that we do not call any object instantiation because it is already handled on our singleton class, how neat is that 💌, and by using singleton, you are guaranteed that only one Logger instance is being used and no more unnecessary instantiation!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FlLkKpUBx8K6be%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fnickelodeon-spongebob-squarepants-finger-guns-lLkKpUBx8K6be&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2FlLkKpUBx8K6be%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/e799934ff123d9cb0f98c3b6c953d08d/href">https://medium.com/media/e799934ff123d9cb0f98c3b6c953d08d/href</a></iframe><p>Kotlin also provide a handy feature if you want to make a singleton class, instead of using companion object, you can just change the <strong>class</strong> keyword into <strong>object</strong> ( notice that this keyword has a lower case of ‘o’ ), for example :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9374e31298e3d6fe473fdad354147a6/href">https://medium.com/media/a9374e31298e3d6fe473fdad354147a6/href</a></iframe><p>Then you could just call it like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb5374ccb6f825bd3cb52de8e10ff452/href">https://medium.com/media/eb5374ccb6f825bd3cb52de8e10ff452/href</a></iframe><p>Even neater and concise right? ;D</p><p>Base on the examples given above, we could see that design pattern provides a solution to problems we might meet when building an app, which can result in a cleaner or a more efficient code. Besides singleton, there is a ton more design patterns waiting for you to explore, i personally would recommended learning from the <a href="https://sourcemaking.com/design_patterns">SourceMaking</a> website, since they cover almost every design patterns out there!</p><p>Using design patterns, you could train yourself on how to build a much more effective code, and learn the best practice on how to solve problems that you might meet during your journey, but keep in mind don’t overuse design patterns, you have to consider several factors before deciding to implement one, here’s a good article telling you when to decide to not use a design pattern.</p><p><a href="https://simpleprogrammer.com/dont-get-obsessed-design-patterns/">Don&#39;t Get Obsessed With Design Patterns</a></p><p>That’s all folks.<br>Happy Coding 🎊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2072458fdcea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bina-nusantara-it-division/design-pattern-why-you-would-probably-need-one-2072458fdcea">Design Pattern : Why You Would Probably Need One</a> was originally published in <a href="https://medium.com/bina-nusantara-it-division">Bina Nusantara IT Division</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All You Need to Know About Swift’s Closure]]></title>
            <link>https://medium.com/bina-nusantara-it-division/all-you-need-to-know-about-swifts-closure-aba836cb90fc?source=rss-7b2dd20adf43------2</link>
            <guid isPermaLink="false">https://medium.com/p/aba836cb90fc</guid>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Arya Surya]]></dc:creator>
            <pubDate>Wed, 21 Oct 2020 08:34:51 GMT</pubDate>
            <atom:updated>2020-10-22T10:06:52.643Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Closures are self-contained blocks of functionality that can be passed around and used in your code.</strong></h4><p>Before you read the article, I assume that you have a basic Swift knowledge,<br>otherwise, you can learn from the official documentation here: <a href="https://swift.org/">https://swift.org/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*TA8Xsk8iDiq4V0_b9o98lA.png" /><figcaption>Photo by Aldo Surya Ongko, image asset from RayWenderlich</figcaption></figure><p>Let’s start with its definition, according to Apple docs, a closure is defined as</p><blockquote><a href="https://docs.swift.org/swift-book/LanguageGuide/Closures.html"><strong>Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.</strong></a></blockquote><p>The definition from Apple is pretty straightforward as we can conclude that closure is just a block of code, or if you would rather call a function, that can be assigned to a variable and reused all over your code, seems handy right?</p><p>If an analogy could help you understand more about the closure, consider this one</p><ol><li>Let&#39;s say <strong>Gon</strong> and <strong>Killua</strong> are eating in a ramen restaurant in Japan</li><li>Gon wants to add some chili to his ramen, but the seasoning box is too far from him, but it is aside from Killua ( because they are practicing social distancing as well ) since it is impolite to talk while eating, Gon decides to write an instruction on a paper to Killua to hand him the seasoning box</li><li>Gon write down HandleMeTheSeasoningBox()<em> </em>on the paper then passed the paper to Killua</li><li>Killua reads the paper then handed the seasoning box to Gon.</li></ol><p>In this case, both Gon and Killua are objects from the Person class, the paper that Gon passed to Killua is a variable, the written HandleMeTheSeasoningBox() instruction on the paper passed to Killua is called a closure ( since it is a function and it is assigned to a variable ).</p><p>Now it kinda makes sense right? Let’s jump to the code :D</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8c8a4afe1c9d04b2a0ca2ff40ed5262/href">https://medium.com/media/b8c8a4afe1c9d04b2a0ca2ff40ed5262/href</a></iframe><p>In the above code, what we did is</p><ol><li>we declare a variable named giveBoxToMe, which contains a <strong>function</strong> thus make itself a <strong>closure</strong></li><li>on line 8 we call the variable, notice that we add parentheses () to the variable, because we are going to “execute” the variable, which itself is a function to be executed</li><li>if you check the variable type ( ⌘ + click + jump to definition ), it will show that giveBoxToMe has a type of ()-&gt;() ( which is proven that closure is just a function, but it stored in a variable hence the variable itself then will have a type of function :D )</li></ol><blockquote>bear in mind that every function has type that follows this format ()-&gt;(), if the function has a string parameter and return void, then its type would be <em>(String)-&gt;()</em>, if it does not have parameter but return an Integer, it would be <em>()-&gt;(Int)</em>, and so on.</blockquote><blockquote>“Wait, is that all about the so-called closure?”</blockquote><p>Well, that is the core of the closure concept, in this post I will explain it as deeply as I can since I found it so useful when developing iOS apps, so bear with me! :D</p><p>As I stated above, a function could have many types, whether it receives a parameter or it returns something, then we know that closure is also a function, hence it could also receive parameters and return something too, consider this example</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b65a5c908139dd93673c6abce18173ce/href">https://medium.com/media/b65a5c908139dd93673c6abce18173ce/href</a></iframe><p>In the code above, we :</p><ol><li>Define another closure, this time our closure takes a string parameter and return nothing</li><li>on line 1, after the = we see something like <br><strong><em>{ name in, the </em>name</strong> is a<strong> closure parameter </strong>referencing to the<strong> outside parameter</strong> passed to the closure ( in this case, the string ) to then be used inside the closure body, that’s why it is called <strong>closure parameter</strong>.</li><li>on line 5, we called our closure like before, but this time we inject a String as it is needed by our new closure, notice how our closure has no named parameters and we could directly pass a string on it.</li></ol><h4>Let’s Recap What we know so far :</h4><ol><li>Closure is just a function.</li><li>Closure could have many types, whether it is a function that receives a parameter and returns something or just a plain void function</li><li>We could pass an argument to a closure, and we could use that passed argument inside the closure body</li></ol><h3>Closure Type Inference</h3><p>Swift is a strongly typed language, the meaning of it is that every variable has a type. even if you don’t specify it explicitly, Swift will do it for you, how awesome it that!. Consider this example</p><p>let isOpen = true</p><p>What is the type of <strong>isOpen </strong>variable? Swift will infer the type based on the context of the value given to the variable, the <strong>true</strong> value is a <em>literal</em> value for a boolean, hence the constant <strong>isOpen </strong>has a boolean type</p><p>You can make use of it in Closure! we can leave parts of our closure expression for Swift to infer what type is it. Consider another example :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66e22f4ef41fc217720e452c08c26d7f/href">https://medium.com/media/66e22f4ef41fc217720e452c08c26d7f/href</a></iframe><p>What we did on the above code :</p><ol><li>We define a variable that is a type of String array</li><li>We then sort them alphabetically by using the function sorted(by:)</li><li>Finally, we print out the result</li></ol><p>When we see inside the sorted(by:) function, we know that it accepts a closure as its parameter, hence we why are only passing a &lt; ?</p><p>If we expand the &lt; , then the function would be like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ece626db261d86c9e74994b4bce6200c/href">https://medium.com/media/ece626db261d86c9e74994b4bce6200c/href</a></iframe><p>It then could be simplified further into</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/577d9af0f55c3918397485f59783be03/href">https://medium.com/media/577d9af0f55c3918397485f59783be03/href</a></iframe><p>We could go even further like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62d1f172199eda7eb5886faae68be1ef/href">https://medium.com/media/62d1f172199eda7eb5886faae68be1ef/href</a></iframe><p>And then we used shorthands arguments</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef22f74567d4dd85c9e603178bd94189/href">https://medium.com/media/ef22f74567d4dd85c9e603178bd94189/href</a></iframe><p>We can omit the parentheses</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb049afcb3cc789936d5113fa75bd378/href">https://medium.com/media/cb049afcb3cc789936d5113fa75bd378/href</a></iframe><p>Then finally we can just use the &lt; as the parameter</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/255f9d59032e7f28e789e0ce7374a903/href">https://medium.com/media/255f9d59032e7f28e789e0ce7374a903/href</a></iframe><p>Very clean right? here’s the detail explanation of each gists :</p><ol><li>The first example uses the complete closure syntax, including two parameter names a and b of type String, and a return type of Bool. Notice that it also has the in and return keywords.</li><li>The second example omits the closure parameter <em>types</em> because they can be inferred from context. Since we’re sorting an array of strings, those two parameters are inferred as String. (When omitting the types, you can also omit the parentheses)</li><li>The third example omits return, because the closure is only one line of code. When that’s the case, Swift figures out that you want to return a value, even if you don’t include return.</li><li>The fourth example uses the $0 and $1 <em>shorthands</em> to reference the first and second parameters of the closure. The parameters are there, they just don’t have names! Again, with inferred String types.</li><li>The fifth example uses <em>trailing closure syntax</em>. When a closure is the last (or only) parameter of a function, you can write the closure <em>outside</em> the function’s parentheses.</li><li>And the last example uses the smaller-than operator &lt; as the closure. In Swift, <em>operators</em> are top-level functions. It’s type is (lhs: (), rhs: ()) -&gt; Bool, and that fits the type of sorted(by:) perfectly!</li></ol><h4>Let’s Recap What we know so far :</h4><ol><li>Swift uses type inference when you do not specify a type of a variable or a function</li><li>You can make use of Swift’s type inference to simplify your closure</li></ol><h3>Closure Capturing in Swift</h3><p>There is one important concept of Closure which I have not explained so far, it is <strong>capturing.</strong></p><p>Swift, just like any other programming language, has something called scope in it. Every variable and function in Swift has a scope. Scope determines whether you can access a particular variable or function. For example, if the function you wanted to execute is not in the same scope as the calling code, then you cannot execute it. For examples :</p><ol><li>A property defined in a class is part of the class scope, it means that anywhere within the class have access to the property ( thus able to set or get the value )</li><li>A variable defined in a function is part of the local function scope, it means that anywhere within the function has to access to the property, and vice versa. ( Anywhere outside the function could not access the variable )</li></ol><p>Consider this example :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e183865957a9e8ab7af5a41d547ca5cc/href">https://medium.com/media/e183865957a9e8ab7af5a41d547ca5cc/href</a></iframe><p>What we did :</p><ol><li>We define a function named calculateCircleArea that takes a double parameter and returns a double value.</li><li>Inside the function, we declare a variable named π and assigned a constant Math PI value to it</li><li>Then we made a closure named area that returns a calculation of π and the radius retrieved from the parameter</li><li>Then we call the calculateCircleArea function with radius parameter 10 and assign it to the result variable</li><li>Eventually, we print out the result</li></ol><p>Wait.. what?</p><figure><img alt="Confused face" src="https://cdn-images-1.medium.com/max/1024/1*d_VVi0wEliUUtr0oZuJo3Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@magdalenakulamanchee?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Magdalena Kula Manchee</a> on <a href="https://unsplash.com/s/photos/confused?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Notice that inline 5 the closure we made have access to the π variable even it is not defined inside the closure scope, that’s because of <strong><em>capturing</em></strong></p><blockquote>A closure has access to the scope it is defined, i.e. π can be retrieved within the closure, even though they were declared in the local function scope</blockquote><p>There are a few things to note :</p><ol><li>A closure only captures variables etc. that are actually used in the closure. When a variable isn’t accessed in the closure, it isn’t captured.</li><li>A closure can capture variables and constants. You can technically also capture other closures because they’re variables or constants too, and properties, because a property belongs to an object that’s assigned to a variable or constant. And you can of course call functions in a closure, but they aren’t captured, because functions aren’t variables (or “stored”).</li><li>Capturing only works one way. The closure captures the scope it is defined in, but code “outside” a closure doesn’t have access to values “inside” the closure.</li></ol><p>Capturing values with closures can lead to all sorts of fun with strong reference cycles and memory leaks, but since it is a big topic, let’s leave that on another post. 👯👯</p><h3>Closure on Action</h3><p>So that we learned about Closure, from its syntax to its ability to capture its surrounding scope, let’s see how we can use this powerful feature in Swift.</p><p>From my code experience, I use closure for 2 scenarios :</p><ol><li>I have a ViewController that has nested children, and on one of those children I need to access the root ViewController’s property and do some logic to it, hence I must create a closure on my root ViewController and passed the closure down to the bottom child who needed it, <strong>it may not be the cleanest way</strong> of doing this but closure is one way to get the job done.</li><li>As a completion handler, we could use closure to do something after a lengthy task, for example, downloading data from the internet, then after the data has been downloaded, we could just show a popup telling the user that their download is already completed.</li></ol><h4>Let’s Recap What we know so far :</h4><ol><li>Closure can access its surrounding scope by <strong>capturing </strong>it</li><li>Closure can be passed around your code</li><li>Closure can be used as a completion handler</li></ol><p>That’s all folks.<br>Happy Coding</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aba836cb90fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bina-nusantara-it-division/all-you-need-to-know-about-swifts-closure-aba836cb90fc">All You Need to Know About Swift’s Closure</a> was originally published in <a href="https://medium.com/bina-nusantara-it-division">Bina Nusantara IT Division</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Dev 101 : Dynamic UITableViewCell]]></title>
            <link>https://medium.com/swlh/ios-dev-101-dynamic-uitableviewcell-8b74f6b53944?source=rss-7b2dd20adf43------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b74f6b53944</guid>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uitableview]]></category>
            <category><![CDATA[uitableviewcell]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Arya Surya]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 15:28:31 GMT</pubDate>
            <atom:updated>2020-06-21T16:30:01.105Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic UITableViewCell in iOS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dws7WMn4UIFjKTkc5LP9LQ.png" /><figcaption>Different UITableViewCell sizes illustration using books.</figcaption></figure><p>As iOS developers, it is a common practice to put your list of data in the cells within the <strong>UITableView</strong>, but one problem always come up to mind for beginners when it comes to implement the <strong>UITableView</strong> to populate their data :</p><blockquote>“ How if the content length of my data varies? how could i make the size of the <em>UITableViewCell</em> to become dynamic as it could fill my content entirely? “</blockquote><p>Because the UITableViewCell itself is a subclass of UIView, which mean it does not have its own <em>intrinsic content size</em>, so we have to define the height of the cell, you could be using UITableViewDelegate or just set the height in the interface builder, but what value should we put in order to make the UITableViewCell’s height dynamic?</p><p>If you search the internet, stack overflow, or any places regarding on how to make the dynamic cells, the answer might be these two lines:</p><blockquote><strong>self.tableView.estimatedRowHeight = 250<br>self.tableView.rowHeight = UITableView.automaticDimension</strong></blockquote><p>So, according to the internet, we only need to put these 2 lines, seems easy huh? But things may have not going accordingly, the UITableViewCells could get clipped or displaying the wrong size, what happen?!</p><p>The truth is, these two lines are already right, we do need to put the value automaticDimension to the row height of the table and not hardcode-ing any value which can result of your cell have a static height of the value you put in, but keep in mind that putting those two are not enough.</p><blockquote><strong>We also need to set the right constraint in our cell so that the AutoLayout Engine could automatically calculate the height / width of our cell.</strong></blockquote><p>For example, if i want to have have a dynamic height of my cell :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8l7KcUz8ASDCxPAZqwxJbA.png" /><figcaption>UITableViewCell</figcaption></figure><p>I need to set the value of A, C, and E, for example i could set the distance from NasiGoreng UILabel to its superview to get A, to the Rp.99999 UILabel to get C, and so forth, so that <strong>the cell knows the distance between each component in my cell from top to bottom thus it could calculate the height automatically</strong>, the B and D value is automatically generated by UILabel since it has <em>intrinsic content size</em>, which means it could calculate the dimension of the content using its font type and size. Another thing that should be noted is <strong>do not set the height constraint of the UILabel</strong>, because it can cause clipping if the text is longer than the height you specified in the constraint, let the UILabel does its job.</p><blockquote>so the AutoLayout Engine is able to determine my cell height by calculating A + B + C + D + E</blockquote><p>If you have UIImageView in your UITableViewCell, you have to first set the image for the UIImageView so that it could gain <em>intrinsic content size</em> just like the previous UILabel case.</p><h3>Conclusion</h3><p>You could make your UITableViewCell has dynamic width and/or height by specifying:</p><ol><li>Set the estimated row height ( could be any value you want, or the average cell height after displaying your content ).</li><li>Set the row height value to UITableview.automaticDimension.</li><li>Do the constraint of the cell properly so that it could resize by itself.</li></ol><p>Happy Coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b74f6b53944" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/ios-dev-101-dynamic-uitableviewcell-8b74f6b53944">iOS Dev 101 : Dynamic UITableViewCell</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>