<?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 Shubham Soni on Medium]]></title>
        <description><![CDATA[Stories by Shubham Soni on Medium]]></description>
        <link>https://medium.com/@imshubham?source=rss-979e15048193------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y9F_gjoTPXG4mGAPWq8gmA.jpeg</url>
            <title>Stories by Shubham Soni on Medium</title>
            <link>https://medium.com/@imshubham?source=rss-979e15048193------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:19:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imshubham/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[Flutter Navigation : Maintaining Tab State While Navigating BottomNavigationBar]]></title>
            <link>https://medium.com/flutter-community/flutter-navigation-maintaining-tab-state-while-navigating-bottomnavigationbar-6009fbceb59c?source=rss-979e15048193------2</link>
            <guid isPermaLink="false">https://medium.com/p/6009fbceb59c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Sat, 28 Nov 2020 15:50:24 GMT</pubDate>
            <atom:updated>2020-11-29T01:18:01.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Navigation : Maintaining Navigation Stack in each Tab while Navigating through BottomNavigationBar</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kc6xmS6kxFQ3jTr93X9XJg.jpeg" /></figure><p>Flutter is fascinating and there’s no competition when it comes to developing beautiful UIs for the mobile. Although once in a while, we stuck on simple things that make our heads turned around. Like I did when I had to maintain the state of individual tabs while navigating through BottomNavigationBar. You can find a great tutorial on the same<a href="https://medium.com/coding-with-flutter/flutter-case-study-multiple-navigators-with-bottomnavigationbar-90eb6caa6dbf"> here</a>, written and explained very well. Even though the article is absorbing, I found it a little complex(Personal Opinion). Then, I decided to do it another way round. I’m not saying mine is better, it’s just my way of doing things.</p><p>We’re going to create a BottomNavigationBar containing four tabs. Each tab will have Listview containing multiple items and each item will navigate to a separate route when tapped. What we have to do is to have maintained the current navigation stack and state of the tab while navigating through the BottomNavigationBar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*tAwuD5BFuK31_4cKX6S5AA.png" /></figure><h3><strong>Step By Step :</strong></h3><p>1) Make a BottomNavBar</p><p>2) Each BottomNavBar Tab will contain a ListView</p><p>3) ListView will have a list of items.</p><p>4) Each Item in the ListView will navigate to a separate route</p><p>5) Maintain the state of the ListView navigation stack while navigating through BottomNavBar</p><p><strong>Enough talk lets just jump into the code and see how it’s done. Before proceeding please make sure you are familiar with these things:</strong></p><ul><li><a href="https://api.flutter.dev/flutter/widgets/IndexedStack-class.html">IndexedStack</a></li><li><a href="https://flutter.dev/docs/cookbook/navigation/navigation-basics">Navigation Basics</a></li><li><a href="https://api.flutter.dev/flutter/foundation/Key-class.html">Key</a></li><li><a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a></li><li><a href="https://api.flutter.dev/flutter/material/MaterialPageRoute-class.html">MaterialPageRoute</a></li><li><a href="https://api.flutter.dev/flutter/material/MaterialApp-class.html">MaterialApp</a></li></ul><h3><strong>Here’s What we gonna do</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*h9606MuYi44vQCOKeU0bvA.gif" /></figure><h3><strong>Let’s Start</strong></h3><p>It&#39;s all about widgets so let&#39;s create our root widget App containing MaterialApp with Homepage() as the home widget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6161b679c8e25786e5b2d1ae9f832292/href">https://medium.com/media/6161b679c8e25786e5b2d1ae9f832292/href</a></iframe><p>Now we’ll create a StatefulWidget called HomePage which will contain the BottomNavigationBar and an IndexedStack so that we can navigate between tabs while maintaining state of each tab. If you don’t know much about IndexedStack please try looking at the docs once.</p><blockquote>IndexedStack is <a href="https://api.flutter.dev/flutter/widgets/widgets/Stack-class.html">Stack</a> that shows a single child from a list of children while maintaining the state of each children in the stack.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36e670d11954394a675abbd0215f75dd/href">https://medium.com/media/36e670d11954394a675abbd0215f75dd/href</a></iframe><p>Here we’re using _pageIndex to keep track of the active index in the IndexedStack which is being shown to the user. Our IndexedStack contains four tabs and each tab shows aNavigatorPage as its child.Hope everything is clear up until now.</p><p><strong>So, now let’s look at the NavigatorPage.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/124196e624e55074220e6d5855112e5e/href">https://medium.com/media/124196e624e55074220e6d5855112e5e/href</a></iframe><p><strong>Things we’re doing in NavigatorPage</strong></p><ul><li>We’re using Navigator and MaterialPageRoute for navigating (Will explain why)</li><li>A ListView containing a list of items.</li><li>Each item when clicked navigate to it’s own DetailRoute .</li></ul><p><strong>So at last we’ll see DetailRoute implementation.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dfeb8c362ef71fcf2a6d13f622029b6/href">https://medium.com/media/3dfeb8c362ef71fcf2a6d13f622029b6/href</a></iframe><p>There’s not much happening here, we’re just showing up an AppBar with Route number on it and a TextField in center with TextEditingController that we’re receiving from NavigatorPage.</p><p>Earlier I mentioned that we’re using Navigator and MaterialPageRoute to navigate in NavigatorPage. You can actually remove both of them, then NavigatorPage will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52dbd30a17cce128dadd2a83b51234d8/href">https://medium.com/media/52dbd30a17cce128dadd2a83b51234d8/href</a></iframe><p>But there’s a problem with this approach, see what we got vs what we want.</p><figure><img alt="what we want VS what we have (Without Navigator and MaterialPageRoute)" src="https://cdn-images-1.medium.com/max/496/1*BXWt-nCm6VQkW6kQhZdr0A.gif" /><figcaption>what we want VS what we got</figcaption></figure><p>Did you notice the BottomNavigationBar in both of them? As you can see if we do not use Navigator and MaterialPageRoute we’ll end up having DetailRoute without BottomNavigationBar. Because when we don’t use Navigatorthen whenever we push any route, the route will be stacked on the default Navigator that comes with MaterialApp.</p><h3>One last thing :</h3><p>We have completed almost everything that we have discussed at the start of this article. Now there’s only one issue with our code. <strong>See this</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*6Uq88MSm6flHqtVxvw_fbA.gif" /></figure><p>Whenever we navigate to DetailRoute and we press the back button, our app closes suddenly. To fix this issue we need to use WillPopScope and GlobalKey. Try to do this by yourself, here are some hints for you:</p><ul><li>Go check WillPopScope and GlobalKey in Flutter docs.</li><li>WillPopScope is a widget that registers a callback to veto attempts by the user whenever he/she presses back button.</li><li>GlobalKey will help you get the BuildContext of current DetailRoute.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*1zJtpLbaGz-ZiaN-2qGYOQ.gif" /></figure><p>If you solved this all by yourself then congratulations on your victory. If not then don’t worry you have tried atleast and here’s an applaud from my side for giving it a shot.</p><p><strong>Now, let’s come to the solution,</strong></p><ul><li>Put WillPopScope as a parent widget to IndexedStack.</li><li>Declare a map containing four GlobalKeys inside HomePage ,one for each of the tabs.</li><li>Pass an asynchronous method to onWillPop parameter of WillPopScope . onWillPop receives a callback that get’s called whenever user presses back button.</li><li>We have to make sure the correct route pops out of the widget tree on back button tap.</li><li>Pass GlobalKeys to NavigatorPage</li><li>Use GlobalKeys received from HomePage as key to the NavigatorPage.</li></ul><p><strong>This is what our HomePage code now looks like after all these changes.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d9fcbaa013bd32aef2b3e8527091900/href">https://medium.com/media/8d9fcbaa013bd32aef2b3e8527091900/href</a></iframe><p><strong>And this will the updated NavigatorPage code.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbaded51ab19e5baec99877390d7027b/href">https://medium.com/media/fbaded51ab19e5baec99877390d7027b/href</a></iframe><h3>☀️ Conclusion :</h3><p>Although as a flutter developer we use Navigator (push &amp; pop) very often but there are few use cases when we actually use Navigator as a widget and this one is the perfect scenario to use Navigator. Also we learned about GlobalKey, MaterialPageRoute, WillPopScope etc. I tried to explain as good as I can, so please pardon me if I couldn’t and let me know where I can improve.</p><p>You can view or download the source code for this article from here</p><p><a href="https://github.com/shubhamhackz/bottomnavbar-multiple-navigator">shubhamhackz/bottomnavbar-multiple-navigator</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*pJV3BuUaC5VAENMXF6Tw4A.gif" /></figure><p><strong>Thanks for reading. If you liked this one, you should </strong><a href="https://medium.com/@shubhamhackzz"><strong>follow me for the next one</strong></a><strong>. 🙏</strong></p><p>Thank to Flutter Community for all the awesome work they are doing on StackOverflow, Github and Pub.</p><p>If you have any questions, feel free to post them 👇.</p><p>Any feedback is welcome 😃.</p><p>If you enjoyed this story, you can support me by 👏 this.</p><p>You can also follow me on <a href="https://twitter.com/shubhamhackz">Twitter</a> , <a href="https://facebook.com/shubhamhackz">Facebook</a> or <a href="https://instagram.com/shubhamhackz">Instagram</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6009fbceb59c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/flutter-navigation-maintaining-tab-state-while-navigating-bottomnavigationbar-6009fbceb59c">Flutter Navigation : Maintaining Tab State While Navigating BottomNavigationBar</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Big Bang Theory of Startup India]]></title>
            <link>https://medium.com/startup-grind/https-medium-com-startup-grind-the-big-bang-theory-of-startup-india-515544f4a17c?source=rss-979e15048193------2</link>
            <guid isPermaLink="false">https://medium.com/p/515544f4a17c</guid>
            <category><![CDATA[entrepreneur]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[startup-india]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[startup-lessons]]></category>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Fri, 04 Jan 2019 16:31:00 GMT</pubDate>
            <atom:updated>2019-01-04T16:31:00.720Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*peTaukz2xid-AHTQVpE9sg.jpeg" /></figure><p>India is now becoming a startup hub. We are so proud as an Indian that our country is growing rapidly, we have big tech companies like Flipkart, Ola etc. As a developing nation today, we need many Startups like Flipkart for truly joining the league of the Western Countries. Our government is also taking some steps toward making business easy in the country. But this isn’t enough to really lead the Startup world when we have an innovative country like the USA which is the origin of almost every big innovation happening today and China which have expertise in making its own version of Western Companies. In case you don’t know China has its own alternative for Google, Facebook, Whatsapp, Amazon etc. Chinese are good at making a clone of each and everything that could be cloned. But wait! What about Indians? What we are doing? Are we really Innovating like the west or cloning like China? Why there’s not even a single Indian company dominating the world like Google, Facebook or Amazon. We will try to figure out and answers to these questions proximately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7l3mUvqYx05CsXB3WWGU2w.png" /></figure><p>If we try to look at some of the successful Indian Startups that have gone from nothing to a billion dollar babies like Flipkart, Snapdeal, Ola, InMobi, Quickr, Paytm, Zomato and many others, you will swiftly begin to notice one thing common to almost all of them, they aren’t really innovative or a new kind of product or something that the world has never seen in the west. Are Indian Startups are almost clones of successful Western Companies?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvgDNONsDPI8cZuf2yZNZw.jpeg" /></figure><p><strong>The short answer is Yes</strong>. Although the market valuation of Indian startups has grown significantly over the past four years, the study, “Entrepreneurial India,” states that 77 percent of venture capitalists surveyed believe that Indian startups lack new technologies or unique business models and 65 percent agrees that there’s a lack of funding. So you may be wondering that what the hell going on? Most of the tech giant has appointed an Indian CEO and here in India, we are cloning the west. Why? Why So?<br>First, take a look at some of the Indian startups and their Western inspiration. These startups seem to heavily influenced by their western inspiration and applied almost the same business model. When you can’t innovate copy. When a new business idea is incubated and executed successfully, cloners naturally emerge and imitate. Its easier to implement an already tested idea with there baked in business model including steps taken by them when they were starting up. Have you ever thought that why Flipkart started by selling books like Amazon did and you would be surprised to know that the founders of Flipkart were ex-amazon employees. However, Amazon did it in 1995, and Flipkart in 2007! Imagine you’re employed by a company and quit to start your own clone of the same company. That’s not innovation in any way.Here’s a short list of Indian versions/clones of the Western Companies, although there’s a lot more.</p><ul><li>Flipkart/Snapdeal → Amazon</li><li>Oyo/Oraval → Airbnb</li><li>Ola → Uber</li><li>Zomato → Yelp</li><li>BookMyShow → Fandango</li><li>MakeMyTrip → Expedia</li><li>Zoho → Salesforce</li><li>iChef/HolaChef → BlueApron</li><li>RazorPay → Stripe</li><li>HealthifyMe → MyFitnessPal</li><li>LensKart → Warby Parker</li><li>naukari.com → Monster.com</li><li>Quickr → OLX</li><li>RedBus → GotoBus</li><li>ZoomCar → Sixt</li><li>CarDekho → TrueCar</li><li>InMob → AdMob</li><li>Grofers → <a href="https://medium.com/u/69f6a3cc42fa">I</a>nstacart</li><li>Yatra → Travelocity</li><li>Mr.Homecare /Zepper → Handy</li><li>Saavn/Gaana → Pandora/Spotify</li><li>Ikea → UrbanLadder</li><li>Mswipe → Squareup.com</li><li>MapMyIndia → GoogleMaps</li></ul><p>Yes, you can say that these are all Indian versions of the western companies what’s wrong with that? Nothing is wrong with them. Every country does this, even the USA have sometimes many clones of some of its companies running in the country. If we want to be a follower of the west till the rest of our existence then this approach is up to snuff. But if we want to lead the way, we’ll have to replace our startups approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-BuU27CD7xyCHM7qY1PEoQ.gif" /></figure><p><strong>This is because of many reasons.</strong></p><ol><li>Society Acceptance Rate</li><li>Insufficient Funding</li><li>We are living in USA’s 2000</li><li>Lack of Risk Takers</li><li>Lack of Innovation</li></ol><h3>1. Society Acceptance Rate</h3><p>Our society is obsessed with the old.We don’t want to replace anything with anything new.If you are from India may be you also heard,”Jaisa chal rha hai chale do” means Let it be how it was and don’t try to be over smart.We are scared of change, you must have seen people running windows 98 even though that launched when dinosaurs ruled the world.People just want to stick to the old things declining new things no matter how good it is.But with this generation it seems to be changing and younger generation is more tolerable and responsive to innovative things.</p><h3>2. Insufficient Funding</h3><p>Most of the Startups in India are Venture Capitalist backed and these VCs seems to be more supportive and convinced with startups which are well tested and materialized in the west than those which are yet to be tested. If you got an innovative idea that’s one of its kind with full of risk then it’s most likely to not get funded easily in comparison to the well-tested ideas. Venture Capitalists in India are looking to play safe, they are not willing to take the risk. If we could change this mindset then we can say a way more diverse ecosystem of startups.</p><h3>3. We are living in USA’s 2000</h3><p>Yes, you heard it right! We are living in USA’s 2000. When we are not even close to our independence in 1911, IBM was founded. When we were busy fighting British, hp was founded in 1939. When we were suffering from Emergency in 1976 Apple was being formed. When the United States was imposing economic sanctions on India, Google, Amazon, Yahoo were already formed or they were being founded in 1998. We missed the industrial revolution and because of all these things we also missed a large chunk or tech innovation. All those years western counties were moving forward and India was yet to figure out all of those. They have founded practically every tech company required for a tech-savvy society. And we are trying to cope with this, resulting in a cloned startup ecosystem.</p><h3>4. Lack of Risk Takers</h3><p>We as an Indian always being taught to not take the risk. We are raised and educated in such a way that taking a risk in our career seems to be a taboo. Our parents, teachers, and society all of them tell us to get good marks, get a job and live a safe life. But I see this is going to change with the power of the young generation because we don’t care less and that’s what makes us different from all those generations lived before us.</p><h3>5. Lack of Innovation</h3><p>In 1996 Mark Zuckerberg was six years old and he was taking programming tuitions and playing with his computer. When we are six or nine, most of the Indian parents don’t allow their children to play with the computer, why? Because they were afraid of what we will do with the computer. When I was 16, I got my first computer and like most of the parents, my parents were also anxious about the kinds of stuff, I was going to do with the computer. But not all Indians are lucky enough to get a full-time computer. Our school and colleges are heavily theory oriented, there’s almost very little or no practical oriented education in India and that’s the main reason behind lacking innovation.</p><h3>Few things to know:</h3><p>In entrepreneurship its not about who does it first, it’s about who did it best. Google was not the first Search engine, Amazon was not the first ECommerce Website, Apple was not the first personal computer, Facebook was not the first social networking website. One thing is common among all of them, they all are inspired in some way with someone else idea. But they did best in their field and ruling the world with their product. If they can do that why can’t we? Why there is not a single Indian company like Google, Facebook, Amazon, Apple which are dominated the whole world. Can’t we have a startup which can rule the world?</p><h3>Last Words:</h3><p>We are copying the west in search of solving our local problems and that’s fine we solved our own problem with our own products like Flipkart, Ola, Paytm instead of solving our problems with western products. But we have to keep one thing in our mind that every Society has its own problem and so we have to find solutions for our own unique problems, maybe that solution could go global and that’s the only way to build a world-class Indian startup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=515544f4a17c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/startup-grind/https-medium-com-startup-grind-the-big-bang-theory-of-startup-india-515544f4a17c">The Big Bang Theory of Startup India</a> was originally published in <a href="https://medium.com/startup-grind">Startup Grind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The curious case of void in dart]]></title>
            <link>https://medium.com/flutter-community/the-curious-case-of-void-in-dart-f0535705e529?source=rss-979e15048193------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0535705e529</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Fri, 21 Dec 2018 13:00:49 GMT</pubDate>
            <atom:updated>2018-12-22T05:47:05.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5HdcaizNnBd7d62_Pz7MQ.jpeg" /></figure><h3>The curious case of void in Dart</h3><p>I think thevoid type is the most curious and subtle type in Dart. As of now, I have got enough experience with Dart that I’m able to explore almost every topic in Dart. But guess what, it surprises me like always. Whenever I began to think that now I have explored all the major parts of the language, it hits me in the head with a brick. At first, it seemed frustrating and difficult to grasp, I tried searching about void on the<a href="https://www.dartlang.org/"> official docs </a>and all other places on the internet that could solve my problem but what I found was just this <a href="https://medium.com/dartlang/dart-2-legacy-of-the-void-e7afb5f44df0">article</a> which opens when you click on the void<a href="https://www.dartlang.org/guides/language/language-tour#keywords"> keyword </a>on the official docs. Since most of my programming days are passed with Java and Android, and Dart is almost similar to Java in comparison to syntax but in some places, it just takes another path far from the way Java does it.</p><h3>😯 What Confuses about void in Dart?</h3><p>If you are coming from Java or some other similar programming language then probably you are comfortable with the thing that method or function with return type void doesn’t returns anything. But in Dart that doesn’t works and void is not that simple to grasp.</p><h4>Initially lets see how void return type behaves in java:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c9a5e54bcb2681eb13e850d281cd829/href">https://medium.com/media/9c9a5e54bcb2681eb13e850d281cd829/href</a></iframe><p>Here, MyVoid is a simple class which contains a method show with return type void . Since the return type is void the method prints <strong>Good Morning World!! </strong>and exits without returning anything. I think things are pretty clear right away but now we will look at how Dart handles void types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da65e2d73ab8236f87b2df10346a522f/href">https://medium.com/media/da65e2d73ab8236f87b2df10346a522f/href</a></iframe><p><strong><em>Note: Every function in Dart returns a value, if you are not declaring it explicitly then null will be returned by default.</em></strong></p><p><em>In the above program either we can return something or we can leave it, if we do not return anything then by default null is returned.</em></p><p>What we are doing here is declaring a top level method show with return type void which is called in the main method, one thing that you should focus on is show method is returning print method which would be invalid in languages like Java. Since in Dart almost everything is an object including functions/methods which are object of class Function and we are allowed to do some more stuff with Function like :</p><ul><li>Declare it as a parameter</li><li>Pass it as an argument</li><li>Assign it to a variable</li><li>Return a function from a function</li><li>Return a result of a function from a function (This is what we are doing above)</li></ul><p>So, now you must understand that Dart functions are no ordinary methods, in fact they are functions on steroid. Now returning to our code above, inside show method we are first executing the method print and after that, we are returning the result of print method.</p><p><strong><em>Note: The return type only specifies what the DartAnalyzer warns you about. There are type checks now in Dart2 that also check that at runtime.</em></strong></p><p>If the return type of show function is void then only three things can be returned, returning any other result will cause a type warning.</p><p>1 ) Return null</p><p>2 ) Return dynamic variable</p><p>3 ) Return void function</p><p>But even if Dart allows to return these three things in a void function, it doesn’t allow us to use these returned values from a void function.</p><h4>For example the code below will not compile:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8401f2d75891bd4f3d840297ab84eeb8/href">https://medium.com/media/8401f2d75891bd4f3d840297ab84eeb8/href</a></iframe><p>Because Dart doesn’t allow us to use the values returned by void functions. Once we change the return type of the show method, we can use the value returned by the method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77f8631d180329f2afcb28f63b481a48/href">https://medium.com/media/77f8631d180329f2afcb28f63b481a48/href</a></iframe><h4>Here, the value = null , do you know why?</h4><p>Inside show method we are executing print method, which will print Good Morning World. If no value is explicitly returned, then null is returned. null is (or would also be) returned when the return type of show is void, but Dart refuses to compile so it doesn’t come to that.</p><h4>😑 Things are more chaotic when we use Shorthand Function () =&gt;</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa1009289ead56402d651426a08b4a27/href">https://medium.com/media/fa1009289ead56402d651426a08b4a27/href</a></iframe><p><strong>Can you guess Is the above program valid or not?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*_qawjcHf6JLY-ILF3gLjZQ.gif" /></figure><p>The program will compile without any error and it is 100% valid. If you guessed it then congrats and if not then don’t think too much about it, as it happened with me also. Yes you can ask that the return types are void then how can we return int , String , bool or a function ? So the answer is you can return anything from a shorthand function with return type void but guess what? You can’t communicate with or use those returned values in any way.</p><p><strong>So why is returning everything allowed through a shorthand function[()=&gt;] even if the return type is void?</strong></p><p><em>As we have discussed above in normal functions with return type </em><em>void we can only return three types of values(i.e </em><em>void , </em><em>null and </em><em>dynamic) but in shorthand function things are little different because shorthand functions always returns a value and if we limit the values that could be returned then functions with </em><em>void return types will become invalid. Lets take an example of setter function as the default return type of every setter is void and they are often declared as a shorthand function.</em></p><p>If you have learned Dart then probably you know that every instance variable in Dart has a getter and setter implicitly. Indeed Dart gives some extra privilege to getter and setter methods treating them like special methods.Look at the code below, here we are setting value to library private instance variable _val using a setter —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a15e1c3b187e32b9a500af4dc9ea8f2/href">https://medium.com/media/0a15e1c3b187e32b9a500af4dc9ea8f2/href</a></iframe><p>Setter are declared using the keyword set in Dart and their return type must be void or absent. If it is absent it is void implicitly. And remember every shorthand function implicitly declares the return keyword, which means you don’t have to declare return keyword instead it is automatically added in the shorthand function. The expression _val = val is an assignment expression and it returns the value assigned. If shorthand functions are not designed in such a way that it allows all types of values to be returned by void then the setter methods will become invalid. You can think of it as a kind of settlement and their’s fair number of discussion going on the topic inside Dart community. Also Dart is an evolving language so you can expect things can change in near future.(and may be not in this case)</p><h3>☀️ One more thing!</h3><p>Until Dart 1 void is only usable as a return types of functions (like void main() ) but from Dart 2(along with static checking, runtime type safety, optional new/const, core library improvements, and more), void has also been generalized. So what does that mean? 🤔</p><p>Dart gives a very gentle way to handle asynchronous code that looks very similar to the synchronous code. I personally like this feature very much. When we are working with <a href="https://www.dartlang.org/guides/language/language-tour#asynchrony-support">Futures</a> , there are many situations when we don’t want to get a result when our asynchronous work is done. Before Dart 2 we have to useFuture&lt;Null&gt; for this but ever since the release of Dart 2, things are better , as now we can do it like this Future&lt;void&gt; .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a20e720abe88d3d5dc7784973e2e647e/href">https://medium.com/media/a20e720abe88d3d5dc7784973e2e647e/href</a></iframe><p>Here I don’t want anything to be returned after the cache is cleared so we are using void as a type parameter. Also we can almost achieve the same thing with Future&lt;Null&gt; . void was not allowed in Dart 1 as generic type parameter and that’s why Future&lt;Null&gt; was used for that purpose.There could be whole lot of other things which we can discuss about them but for now just keep in mind that void will allow to return any value but you can’t use or communicate with the values returned(if you try to do so, you will get a warning) and Null only allows to return null .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-ZYuoGauFjWQe0xgPQZ3aA.gif" /></figure><p><strong>Thanks for reading. If you liked this one, you should </strong><a href="https://medium.com/@shubhamhackzz"><strong>follow me for the next one</strong></a><strong>. 🙏</strong></p><p>Thank You <a href="https://twitter.com/gzoechi">Günter Zöchbauer</a> for the Proofreading and for all the awesome work you are doing on Stackoverflow for the Dart Community.</p><p>If you have any questions, feel free to post them 👇.</p><p>Any feedback is welcome 😃.</p><p>If you enjoyed this story, you can support me by 👏 this.<br>You can also follow me on <a href="https://twitter.com/shubhamhackz">Twitter</a> , <a href="https://facebook.com/shubhamhackz">Facebook</a> or <a href="https://instagram.com/shubhamhackz">Instagram</a>.</p><p><a href="https://twitter.com/FlutterComm">JavaScript is not available.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0535705e529" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/the-curious-case-of-void-in-dart-f0535705e529">The curious case of void in dart</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart for Flutter : Mixins in dart]]></title>
            <link>https://medium.com/flutter-community/https-medium-com-shubhamhackzz-dart-for-flutter-mixins-in-dart-f8bb10a3d341?source=rss-979e15048193------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8bb10a3d341</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[mixin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Sat, 15 Dec 2018 08:53:30 GMT</pubDate>
            <atom:updated>2018-12-20T09:11:32.583Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dart for Flutter : Mixins in Dart</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ir8rIg1_YvZgH_4F11RaBg.gif" /><figcaption>Mixin Classes</figcaption></figure><p>I’m an Android developer with a lot of Java and general programming experience. This year Flutter has received a lot of exposure from its beta release, attracting many developers from Android, IOS and even from the web.</p><p>After the release of Flutter 1.0, it has peeked the curiosity of almost every mobile developer. When I first looked at it, it seemed very interesting so I decided to give it a shot.</p><p>When I realized that I have to learn a new programming language to start with Flutter, I almost planned to skip trying it. Learning a new programming language is always a time consuming process. That said, when I looked at some of the examples on Dart’s website, everything changed. Dart feels like home. It is a very clean and easy to understand language, especially if you have a programming background in languages such as Java, JavaScript, C# or any other <em>object-orientated programming</em> language. You will be up and running Dart programs in a matter of hours.</p><p>From my time with Dart, one topic which I feel is a little tricky is <strong>mixins</strong>. For Java developers, it is a completely new concept to learn as Java does not supports multiple inheritance or <em>mixins</em>. Java tries to make up for this by using Interfaces, but that is not as useful or flexible as <em>mixins</em>.</p><p>So, lets first try to understand what is <em>mixins</em>?</p><h3>💫 What mixin really is?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*p-uFfabN7LHsK-OBZHezyQ.gif" /></figure><p>I think the most concise definition of <strong>mixin</strong> is provided by <a href="https://en.wikipedia.org/wiki/Mixin">Wikipedia</a>:</p><blockquote><em>“In object-oriented programming languages, a </em><strong><em>Mixin</em></strong><em> is a class that contains methods for use by other classes without having to be the parent class of those other classes.”</em></blockquote><p>In other words<strong> mixins</strong> are normal classes from which we can borrow methods(or variables) from without extending the class. In dart we can do this by using the keyword with. If you want to use class B as a mixin for class A then :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0390d6cb68068dfef4cd818e63ddd045/href">https://medium.com/media/0390d6cb68068dfef4cd818e63ddd045/href</a></iframe><p>The code class A with B is equivalent to class A extends Object with B . Right now, classes can only be used as <em>mixins </em>once they only extend object. Classes which extend other classes cannot be used as a <em>mixin</em>. This could change in the future however since Dart is continuously evolving and there is already an experimental feature which allows us to use <em>mixins </em>which extends class other than Object . Maybe at the time of reading this article there could be some minor changes how mixins behave. So always keep an eye on <a href="https://github.com/dart-lang/language/blob/master/accepted/2.1/super-mixins/feature-specification.md#dart-2-mixin-declarations">mixin specifications</a>.</p><p>Although we can’t use mixin class which extends class other than Object, we can extends or implement the base class(Class A in this example) which is using mixin class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7101c7771ba76d0a2e1d1068c4b1d41/href">https://medium.com/media/f7101c7771ba76d0a2e1d1068c4b1d41/href</a></iframe><p>Mixins enables a programming language to mimic an benefit from features such as multiple inheritance and code reuse while also reducing the risk of running into problems such as the <a href="https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem">Deadly Diamond of Death(DDD)</a>.</p><p>Some people describe mixins as an interface with implementations.</p><h3><strong>😨 What is deadly diamond of death(DDD) in multiple inheritance?</strong></h3><p>Suppose we have an abstract class called Performer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/350fac509f6bcd2da6d9743b6436b536/href">https://medium.com/media/350fac509f6bcd2da6d9743b6436b536/href</a></iframe><p>Now we will make two concrete classes Dancer and Singer which extends Performer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3c31b34eb7b031864e99d4a53d37f60/href">https://medium.com/media/b3c31b34eb7b031864e99d4a53d37f60/href</a></iframe><p>Extending Performer is the only way I can dance and sing.</p><p><strong><em>Now suppose dart supports multiple inheritance and a class called Musician extends both the classes Dancer and Singer.</em></strong></p><blockquote><strong>Note: Dart only supports Single inheritance, I’m just assuming here, what will happen if dart supported Multiple Inheritance like C++:</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/711067442edb129bbe5fda1742287de0/href">https://medium.com/media/711067442edb129bbe5fda1742287de0/href</a></iframe><p>Can you guess which perform() method will be called in Musician class?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*k28mWAKSCZN-_YWyFrOX6w.jpeg" /></figure><p>Confused? This is what a compiler feels when we try to run this code.Because there’s no actual way for us to decide which is the right method to call. This very situation is known as deadly diamond of death and it is a core problem of multiple inheritance. Thankfully, we can fix this using mixins.</p><h3>😍 What mixin can do for us?</h3><p><a href="https://www.dartlang.org/guides/language/language-tour#adding-features-to-a-class-mixins">As the official docs states</a>:</p><blockquote>“To <em>implement</em> a mixin, create a class that extends Object and declares no constructors. Unless you want your mixin to be usable as a regular class, use the mixin keyword instead of class.”</blockquote><p>The mixin keyword was introduced in dart 2.1 and it is analogous to abstract class in some ways and different from it in other way. Like abstract class, you can declare abstract methods in mixins and it cannot be instantiated. But unlike abstract , you can’t extend a mixin.</p><p>You can either use the keyword mixin, abstract class or a normal class as a mixin. Let’s take a look at how we can solve the above problem with mixins.</p><p>Always keep in mind that mixin is not multiple inheritance instead they are just a way to reuse our code from a class in multiple hierarchies without needing to extend them. Its like being able to use other people assets without being their children. Its cool hah! 😝</p><p>First we have to create our Performer class with method perform() ,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cf311d2d89c64462c322c916f929c26/href">https://medium.com/media/2cf311d2d89c64462c322c916f929c26/href</a></iframe><p>Next we create the class Dancer which contains a method named perform()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f93ea71d1a801fe9ced57791d50de877/href">https://medium.com/media/f93ea71d1a801fe9ced57791d50de877/href</a></iframe><p>Now we will declare another class called Singer which will contain the same method perform()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e983fdcef35b452e1bd29e74900fbac/href">https://medium.com/media/7e983fdcef35b452e1bd29e74900fbac/href</a></iframe><p>Lets create one more class Musician which will use both of these classes along with Performe class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a31d9d10027e800c2edd8f26c5fc53c/href">https://medium.com/media/2a31d9d10027e800c2edd8f26c5fc53c/href</a></iframe><p>Now if we try to run the above code, we will get the output lalaaa..laaalaaa....laaaa , can you guess why ?</p><p>When mixing classes, the classes used as <em>mixins </em>are not parallel but instead on top of the class using it. This is the reason why methods do not conflict with one another, allowing us to use codes from multiple classes without having to deal with the vulnerabilities of multiple inheritance.</p><p>If you are confused by this, don’t panic, I will explain how mixins are evaluated.</p><p>For determining which class method will be executed when using mixins, follow these simple steps:</p><ul><li>If the class using mixins is extending any class then put that class on top of the stack. i.e class Musician extends Performer</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*rUrxDkdla3cBsquM64J2wQ.jpeg" /></figure><ul><li>Always remember the order in which you declare mixins, this is very important because it decides which class is more important. If mixins contains identical methods then the mixin class that is declared later will be executed(Declaring a mixin after another raises its “Importance”).</li></ul><p>In our example, we declared Dancer before the Singer, so it is more “Important”and therefore would go below Performer . I.e class Musician extends Performer with Dancer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*n2xlbk329Hlv29B5Y5CMWw.jpeg" /></figure><ul><li>After Dancer we declared Singer , so put the Singer below Dancer in the stack :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*WbOzfx7GcUnhebymJZPLEg.jpeg" /></figure><ul><li>Finally, add the class which is using mixins i.e Musician into the stack. This class would be the most important or most specific class.If this class contains any identical methods to mixins or super class then the methods in this class would be called first…always.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*lxRghguALEkvYDNmc0Ykgw.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FCHyxN9bNkMc3S%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FCHyxN9bNkMc3S%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FCHyxN9bNkMc3S%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="235" frameborder="0" scrolling="no"><a href="https://medium.com/media/56856e22a7f20822370a3adac53fb956/href">https://medium.com/media/56856e22a7f20822370a3adac53fb956/href</a></iframe><p>Got it? The idea behind how mixins can be used as a way to reuse code without having to deal with multiple inheritance and the problems which arise because of it.</p><p>Now we will try to focus on some other advanced stuffs that we can do with mixins.</p><h3>😯 Doing some more stuff with mixin!</h3><p>Although we can do many normal and advanced stuff using Dart’s mixins, there is one more thing which we need to look at and that is the keyword on. The keyword on is used to restrict our mixin’s use to only classes which either extends or implements the class it is declared on. In order to use the on keyword, you must declare your mixin using the mixin keyword.</p><p>Below is an example of using the On keyword:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9445813c4427fdf0c9cfcdef506c0a0/href">https://medium.com/media/d9445813c4427fdf0c9cfcdef506c0a0/href</a></iframe><p>In the above code we are restricting mixins Xand Y to be only used by the classes which either implements or extends A and B respectively.</p><h3>☀️ Conclusion :</h3><p>The roots of mixins can be found in <a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)">Lisp</a> Community and its very first uses to <a href="https://en.wikipedia.org/wiki/Smalltalk">smalltalk</a>. Dart is influenced by smalltalk in many ways, it takes many inspirations from it including mixin. Mixins are great way for reusing your code without any restrictions in multiple class hierarchies. I believe that there are lots of things which could be done using mixins. I would love to see what you all create with this. Good Luck ! Happy Fluttering!</p><p>If you have any questions, feel free to post them 👇.</p><p>Any feedback is welcome 😃.</p><p>If you enjoyed this story, you can support me by 👏 this.<br>You can also follow me on <a href="https://twitter.com/shubhamhackz">Twitter</a> , <a href="https://facebook.com/shubhamhackz">Facebook</a> or <a href="https://instagram.com/shubhamhackz">Instagram</a>.</p><p><a href="https://twitter.com/shubhamhackz">Shubham Soni (@shubhamhackz) | Twitter</a></p><p>Follow Flutter Community:</p><p><a href="https://twitter.com/FlutterComm?lang=en">https://twitter.com/FlutterComm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8bb10a3d341" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/https-medium-com-shubhamhackzz-dart-for-flutter-mixins-in-dart-f8bb10a3d341">Dart for Flutter : Mixins in dart</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Udacity’s Scholarship changed a Dropout’s Life!]]></title>
            <link>https://medium.com/code-yoga/how-udacitys-scholarship-changed-a-dropout-s-life-37b1c251abec?source=rss-979e15048193------2</link>
            <guid isPermaLink="false">https://medium.com/p/37b1c251abec</guid>
            <category><![CDATA[google-scholar]]></category>
            <category><![CDATA[dropout]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[udacity]]></category>
            <category><![CDATA[ourstory]]></category>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Sat, 31 Mar 2018 09:26:13 GMT</pubDate>
            <atom:updated>2018-04-03T04:50:43.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*vFnWg55OPhmu6Rl2fVFvaA.jpeg" /></figure><p>I’m a University Dropout Student and a programmer.I just love the idea of programming ever since I got to know about it.I live in a society where barely anyone knows what a programming language is and what is it used for.I have been using computers since the 6th standard for playing games, games and more games.I have played every game that my computer could support(If you know most awesome games has most advanced requirements).When I was in 11th Standard I have taken computer science and was only student in my school to take Computer Science.I don’t know why anyone didn’t take CS apart from me but It turned into fun for me.I use to take my Laptop to the Computer Lab and stay there almost whole time after making my attendance.I passed 12th standard with 71.6% and failed to get admission into any Reputed University.Also, I don’t have much money to take admission through donation(Indian Students Could Understand).In a country where everyone judges with your marks it is so embarrassing to satisfy anyone with this marks.At last, I headed towards a local University and taken admission.In Bihar Universities are there to only take exams and give your degree.There’s nothing for you “no class, no attendance, no lectures nothing!” So, I chose to be a dropout rather than holder of a freely given degree.</p><p>After all this, I decided to become a programmer and I started from java and hit the books, searched all over the internet and also furrowed into the open source community.But even after seeking all these places, I always missed something.One mourning I got a mail from Udacity saying “We are excited to offer you a Google India Challenge Scholarship for the Android Developer track”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*xAvk9wCP10gKjNuoYFxX0g.png" /></figure><p>I was amazed and shocked, it was a mixture of some feeling simultaneous bursting out.Because when you feel joining something connected to Google or Udacity it feels like you have hit the Jackpot!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*G27j6lUdO-a8-CP2SSdKFA.gif" /></figure><p>Until then I never thought about the things going to happen in my life, as I thought it was going to be a simple video-lecture course.Then I started my course joining Slack and Forum.I was mesmerized sensing So many like-minded people in one place.I discovered how we can help each other, learn and solve problems together.Although the course material was awe-inspiring and better than books.The best thing Udacity gifted was the community and its members.I love how everyone helps and contribute to the community.This community isn’t just for this course instead Udacity joined us and formed a community for Life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*YuA8aaRq1Mj12QZ7NgZMWw.jpeg" /></figure><p><strong>Yes</strong>, yes I know that’s not the actual photo of our <strong>community</strong> but it is damn close to the community.Everyone is unique in its own manner and knows how to make the community more awesome. Everyone there on<strong> Slack and Udacity</strong> Forum seems to have some sort of hidden superpower as they give up everything to solve any problem.</p><p>Yes, I missed the community and the art of learning together.I was astonished and glad that <strong>Google</strong> and<strong> Udacity </strong>had given me this chance to take my life into a better direction.Now, I know degree doesn’t matter, knowledge does.And if we have a such an community where knowledge is flowing from every corner, then its not hard to learn and achieve anything.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37b1c251abec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-yoga/how-udacitys-scholarship-changed-a-dropout-s-life-37b1c251abec">How Udacity’s Scholarship changed a Dropout’s Life!</a> was originally published in <a href="https://medium.com/code-yoga">Code Yoga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some great alternatives for AsyncTasks]]></title>
            <link>https://medium.com/code-yoga/some-great-alternatives-for-asynctasks-e8113747673a?source=rss-979e15048193------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8113747673a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[threading]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[background-task]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Fri, 30 Mar 2018 06:54:55 GMT</pubDate>
            <atom:updated>2018-03-30T07:09:10.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QdyQF8WjBzcQwFVYs3dsrg.jpeg" /></figure><p>AsyncTask manages a thread pool, from which it pulls the threads to be used by task instances. Thread pools assume that they will get their threads back after a reasonable period of time. Hence, AsyncTask is a poor choice when you do not know how long you need the thread (e.g., thread listening on a socket for a chat client, where you need the thread until the user exits the client).</p><p>If you create an AsyncTask that uses an activity context or the AsyncTask is and child of the activity/fragment, you keep the activity/fragment in memory. When you rotate or change activity in the period the AsyncTask is running. you keep your old activity instance in memory and are leaking the activity/fragment or If you are using an AsyncTask as a child of an Activity/Fragment or it uses the context of the Activity then it will keep the activity/fragment running in the memory even after the new ones are created.Like if you rotate the activity the AsyncTask will keep running making your old Activity instance Alive in the memory causing memory leaks…Here You have two options.</p><ul><li>@SuppressLint(“StaticFieldLeak”) — Ignore the LINTs warning</li><li>Make you Inner nested Class static or use Top level Class instead if Using anonymous, local, and inner class.</li></ul><p>If you are using an AsyncTask then you have to deal with this…either this or that way…</p><p>So lets look at some of great alternatives for replacing AsyncTasks and making our life much easier..</p><h4><strong>• AsyncTaskLoader</strong> :</h4><p>AsyncTaskLoader performs the same function as the AsyncTask, but a bit better. It can handle Activity configuration changes more easily, and it behaves within the life cycles of Fragments and Activities. The nice thing is that the AsyncTaskLoader can be used in any situation that the AsyncTask is being used. Anytime data needs to be loaded into memory for the Activity/Fragment to handle, The AsyncTaskLoader can do the job better.</p><p>When compare <strong>AsyncTaskLoader</strong> vs. <strong>AsyncTask</strong>, as you may know when you rotate your device screen, it may destroy and re-create your activity, to make it clear let image rotate your device while networking transaction is going on:</p><p><strong>AsyncTask</strong> will be re-executed as background thread again, and previous background thread processing was just be redundant and zombie.</p><p><strong>AsyncTaskLoader</strong> will be just re-used basing on Loader ID that registered in Loader Manager before, so avoid re-executing network transaction.</p><h4><strong>• Volley</strong> :</h4><p>Volley is a library that makes networking for Android apps easier and most importantly, faster.Volley automatically schedule all network requests. It means that Volley will be taking care of all the network requests your app executes for fetching response or image from web.</p><p>Advantages of Volley are:</p><ul><li>Volley provides transparent disk and memory caching.</li><li>Volley provides powerful cancellation request API. It means that you can cancel a single request or you can set blocks or scopes of requests to cancel.</li><li>Volley provides powerful customization abilities.</li><li>Volley provides Debugging and tracing tools</li></ul><h4><strong>• Retrofit :</strong></h4><p>It’s released by <a href="http://square.github.io/retrofit/">Square</a>, This offers very easy to use REST API’s.</p><ul><li>Compared to Volley, Retrofit’s REST API code is brief and provides excellent API documentation and has good support in communities! It is very easy to add into the projects.</li><li>We can use it with any serialization library, with error handling.</li></ul><h4><strong>• RxJava :</strong></h4><blockquote>Its an better approach to RxJava instead of AsyncTask wherever possible.RxJava is “a library for composing asynchronous and event-based programs by using observable sequences”.While they can’t be compared directly but allows you to write less code to do the same.</blockquote><p>Let’s say you have a login form. A naive implementation would be a direct chain of method calls, starting with your UI, like:</p><ol><li>user clicks the button</li><li>initiate login request</li><li>return the results of login request</li><li>update UI</li></ol><p>What happens when a config change occurs between #2 &amp; #3? Your chain of method calls is broken, because your activity is gone. A better approach:</p><ol><li>Observe results/exceptions of login calls from UI</li><li>User clicks login button</li><li>UI serializes a future attempt to login</li><li>Data/Network layer observes this serialization, executes a new network request, completely independent of your UI layer</li><li>Because UI is already observing login call results (#1), your UI will be updated</li></ol><p>So instead of a single LoginResult loginWith(Credentials credentials) method, I have two:</p><ul><li>Observable&lt;LoginResult&gt; logins() (I&#39;ll begin observing this in onStart())</li><li>void loginWith(Credentials credentials)</li></ul><p>This allows you to observe the results of the call separately from initiating it.</p><h4>• <strong>Services :</strong></h4><blockquote>Services are a “Swiss Army knife” for a wide range of functions that do not require direct access to an activity’s user interface.</blockquote><p>AsyncTask manages a thread pool, from which it pulls the threads to be used by task instances. Thread pools assume that they will get their threads back after a reasonable period of time. Hence, AsyncTask is a poor choice when you do not know how long you need the thread (e.g., thread listening on a socket for a chat client, where you need the thread until the user exits the client).</p><p>AsyncTasks are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed.</p><p>Services are designed to be continually running in the background. In the example above of fetching data when a button is pressed, you could start a service, let it fetch the data, and then stop it, but this is inefficient. It is far faster to use an AsyncTask that will run once, return the data, and be done.</p><h4><strong>• AsyncTaskScheduler :</strong></h4><p>Another alternative for AsyncTask<strong>.<br></strong>1.<strong> </strong>execute tasks in parallel as default, rather than processing them sequentially</p><p>2. execute single task use a thread rather than an executor</p><p>3. you can set a default executor to execute tasks</p><p>4. a callback for task error</p><p>5. manage multiple tasks easily</p><p>6. you can you it on any thread ,anf it will have a callback on main thread。</p><h4>• <strong>LoopJ :</strong></h4><p>An asynchronous, callback-based Http client for Android built on top of Apache’s <a href="http://hc.apache.org/httpcomponents-client-ga/">HttpClient</a> libraries.</p><ul><li>Make asynchronous HTTP requests, handle responses in anonymous callbacks</li><li>HTTP requests happen outside the UI thread</li><li>Requests use a threadpool to cap concurrent resource usage</li><li>GET/POST params builder (RequestParams)</li><li>Multipart file uploads with no additional third party libraries</li><li>Tiny size overhead to your application, only 60kb for everything</li><li>Automatic smart request retries optimized for spotty mobile connections</li><li>Automatic gzip response decoding support for super-fast requests</li><li>Optional built-in response parsing into JSON (JsonHttpResponseHandler)</li><li>Optional persistent cookie store, saves cookies into your app’s SharedPreferences</li></ul><h4><strong>• Thinr :</strong></h4><p>Thinr is a replacement for AsyncTask. It is a tiny library that makes things like the following possible in a leak free and configuration change aware way.</p><ul><li>easy usage</li><li>easy to understand</li><li>no boilerplate code involved (when using Java 8)</li><li>easy to integrate</li><li>no need to rewrite your whole code base to make use of it / can be introduced step-by-step where it is needed while leaving all the other code untouched</li><li>non invasive (i.e. don’t forces you to use a special style of programming)</li><li>beautiful code (when using Java 8)</li></ul><h4><strong>• Futuroid :</strong></h4><p>Futuroid is an Android library that allows running asynchronous tasks and attaching callbacks thanks to a convenient syntax. It offers an alternative to the Android <a href="http://developer.android.com/reference/android/os/AsyncTask.html?utm_source=android-arsenal.com&amp;utm_medium=referral&amp;utm_campaign=1196">AsyncTask</a> class.</p><ul><li>Future-based API (similar to Guava’s ListenableFutures, Scala/Akka Futures, Javascript promises…)</li><li>Allows registering callbacks to be run on the Android UI/main thread</li><li>Provides a default ExecutorService (fixed thread pool with 5 threads) that can be replaced by a custom one</li><li>Each task can be run on the default ExecutorService or on a custom one</li><li>Allows task chaining (monad-style)</li></ul><h4>• BoltsFrameworks :</h4><p>Bolts is a collection of low-level libraries designed to make developing mobile apps easier. Bolts was designed by Parse and Facebook for our own internal use, and we have decided to open source these libraries to make them available to others.Bolts Tasks have many advantages over other methods of asynchronous programming, such as callbacks and AsyncTask.</p><ul><li>They consume fewer system resources, since they don’t occupy a thread while waiting on other Tasks.</li><li>Performing several Tasks in a row will not create nested &quot;pyramid&quot; code as you would get when using only callbacks.</li><li>Tasks are fully composable, allowing you to perform branching, parallelism, and complex error handling, without the spaghetti code of having many named callbacks.</li><li>You can arrange task-based code in the order that it executes, rather than having to split your logic across scattered callback functions</li></ul><h4>• Needle :</h4><p>Its an Multithreading library and a good alternative for asynctasks.</p><h4><strong>• Nanotasks :</strong></h4><p>NanoTasks is an extremely light way to execute code in the background on Android. It is a wrapper around AsyncTask that provides a simpler to use and more flexible API.</p><h4>• TeaSpoon :</h4><p>It makes more clear and easy to execute your method on ui thread or background thread.</p><ul><li>Eliminate runOnUiThread calls by using @OnUi on method.</li><li>Make background logic more clear by using @OnBackground on method.</li></ul><h4>• SugarTask :</h4><p>Another simple and good alternative for AsyncTask.SugarTask is so simple that it just works good for easy task and simple Tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8113747673a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-yoga/some-great-alternatives-for-asynctasks-e8113747673a">Some great alternatives for AsyncTasks</a> was originally published in <a href="https://medium.com/code-yoga">Code Yoga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala The Lost Legend of Android]]></title>
            <link>https://imshubham.medium.com/scala-the-lost-legend-of-android-c0732d4670dc?source=rss-979e15048193------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0732d4670dc</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Fri, 16 Mar 2018 19:21:20 GMT</pubDate>
            <atom:updated>2018-03-16T19:21:20.244Z</atom:updated>
            <content:encoded><![CDATA[<p>I know everyone is talking about Kotlin and how things are changing when we use kotlin but today I’ going to get you a quick look about how things could be if we use Scala instead of Java in Android.Moving away from a well established and mature language such as Java requires some pretty good reasons. Before pragmatically trying out some of the apparent differences between Java and Scala in order to get acquainted with the Scala syntax, we are going to clarify what makes Scala so attractive.Working with Scala on Android is a real joy. Its syntax helps in writing less code, and cleaner code.</p><p>Scala surfaced to the general public in the year 2004. Developed by Martin Odersky, Scala was released on the Java platform as a general-purpose programming language. The name Scala is not some whimsical notion, it is an abbreviation of “scalable”: a language that is scalable according to the needs of its users.</p><h4>Full Support for Pattern Matching, Macros, and Higher-Kinded Types</h4><p>Pattern matching in Scala is no joke. Scala uses the <em>match </em>statement for this purpose, which is a powerful version of Java’s switch statement. It allows you to match on any type of data, lists, and even your own types. If you haven’t already tried it, I suggest you play around with it a little.</p><h4>Write Once, Run Everywhere</h4><p>Scala is a little complex, but it has a very flexible code syntax. The proficient use of functional programming features makes the code extensible and hierarchical to the very best level.</p><h4>Bigger Community Support</h4><p>Scala has been here for more than a decade. Since it is a powerful Java alternative, it has huge support community. We’re talking about YouTube tutorials, blog posts, forums, and let’s not forget the official support and user documentation. Anything you find yourself struggling with, you can pretty much find the answer to it.</p><h4>Operator Overloading</h4><p>Scala does not restrict you from overloading operators. You can play with operator-looking functions and define limitlessly. But you need to be careful with this feature. Still, if you can do this right, your code readability will increase. If not, you might end up making your code difficult to understand.</p><h4><strong>Use implicit type conversions</strong></h4><p>Scala offers us a very powerful tool. By declaring a function as implicit, it will be used by the compiler to directly convert a type to another.</p><p>Take a look at the following code, setting up an OnClickListener for a button:</p><pre>var button=findViewById(R.id.button).asInstanceOf[Button]<br>  button.setOnClickListener(new View.OnClickListener){<br>    def onClick(v:View) {<br>      <strong>Toast</strong>.makeText(<strong>this</strong>, &quot;Clicked&quot;, <strong>Toast</strong>.<strong>LENGTH_LONG</strong>).show()<br>    }<br> })</pre><p>Yes, we need to create a new instance of the OnClickListener and override its onClick method. Doing that for each and every button is cumbersome.</p><h4>With implicit conversions, we can get a much better syntax. First, let us define a Helpers object:</h4><pre>import android.view.View<strong><br></strong>objectHelpers{<br>  implicit def<strong> </strong>onClick(handler<strong>: </strong>View =&gt; Unit)<strong>:</strong>View.OnClickListener<strong> </strong>=       new View.OnClickListener(){<br>    override def onClick(source<strong>: </strong>View) <strong>= </strong>handler(source)<br>  }<br>}</pre><p>We wrote a method to convert a function taking a View as argument and returning nothing, to an OnClickListener instance. What can we do with that? We can now change the code like this:</p><pre><strong>importHelpers._<br></strong>[<strong>…</strong>] <br><strong>val</strong>button<strong>=</strong>findViewById(R.id.button).asInstanceOf[<strong>Button</strong>]<br>   button.setOnClickListener((v <strong>: View</strong>) <strong>=&gt; </strong>{ <strong>Toast</strong>.makeText(<strong>this</strong>,         “Clicked”, <strong>Toast</strong>.<strong>LENGTH_LONG</strong>).show()<br>   })</pre><p>Isn’t that cleaner? And you can apply the same idea to other listeners, like OnLongClickListener.</p><p>Although its completely on you what you want to use in your code.Yes,I agree if you want to go simple and easier then definetely go with kotlin but for places where you need to handle large amounts of data or complex modeling reliant on mathematics, or simply if you need more power with cleaner code then, Scala would be best.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0732d4670dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI(Model-View-Intent) Pattern in Android]]></title>
            <link>https://medium.com/code-yoga/mvi-model-view-intent-pattern-in-android-98c143d1ee7c?source=rss-979e15048193------2</link>
            <guid isPermaLink="false">https://medium.com/p/98c143d1ee7c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Fri, 16 Mar 2018 11:25:36 GMT</pubDate>
            <atom:updated>2018-03-29T11:29:55.648Z</atom:updated>
            <content:encoded><![CDATA[<p>As an Android Developer we come to hear these words MVC,MVP,MVVM daily and we have to decide which architectural pattern we have to use in our app.Today we are going to give a quick look on a architectural pattern which is not so popular in android world but have good grip on the Javascript Community.MVI is introduced by <a href="https://cycle.js.org/">Cycle.js</a>(JavaScript FrameWork) by André Staltz and it is also used in other popular javascript Frameworks like <a href="https://redux.js.org/">Redux</a>.</p><p>In Android the MVI Pattern is adopted by Android enthusiast and open source lover <a href="http://hannesdorfmann.com/">Hannes Dorfmann</a>. So,lets go and look what the heck MVI pattern looks like!</p><h4><strong>Model-View-Intent</strong></h4><p>The major GUI architectures, MVI is defined fairly loosely. However, at its core, it is a return to the unidirectional data flow that MVC offered… though with few more parts:”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*qBNRArLl5XrsR0Kh_FPI2A.png" /></figure><ul><li><strong>Intent-Intent is not Intent. </strong>The intent simply describes an intention, or action, or command generated by the user as he or she is interacting with the app.An intent represents the interaction with the view by the user. The intent delivers changes that need to be processed by the Model.</li><li><strong>View</strong>- The view, actual the UI, observes and depicts the model’s state. The view forwards each interaction as intent.</li><li><strong>Model-</strong> Model<strong> </strong>represents a state (data to be displayed, visibility of your View widgets, RecyclerView scroll position, etc.).This includes interactions with business logic. The business logic updates the current state and thereby the observing View.</li></ul><p>If you going going to implement MVI (Model-View-Intent) in your app then instead of starting from scratch you can use <a href="https://github.com/sockeqwe/mosby">mosby</a> library developed by Hannes Dorfmann. Ofcourse it is not mandatory that you should start with a third party library in order yo implement MVI pattern in your app.One advantage of using<a href="https://github.com/sockeqwe/mosby"> mosby </a>library is that you get the base classes on which you can build you app.</p><h3>Differences between MVI and MVP</h3><p><strong><em>Model-View-Presenter (MVP)</em></strong><em> is a software architectural pattern which is based on Model-View-Controller. It is used to implement user interfaces while keeping the model seperated from the view. The interactions are controlled by the presenter which acts as an mediator between model and View.</em></p><p><strong><em>Model-View-Intent (MVI)</em></strong><em> is also a derivation of the original MVC architectural pattern. The pattern fulfills the essential purpose of the original MVC as dicussed by André Staltz in his </em><a href="https://cycle.js.org/model-view-intent.html#model-view-intent-what-mvc-is-really-about"><em>description of MVI</em></a><em>. Instead of working with a proactive controller MVI works with the reactive component called intent.</em></p><p><strong>Model-View-Presenter:</strong></p><ul><li>Seperation between model and view. The presenter acts like a mediator.</li><li>One to one mapping between View and Presenter, with the possibility to use multiple Presenters for more complex Views</li></ul><p><strong>Model-View-Intent:</strong></p><ul><li>Unidirectional Flow allows us to work without callbacks between the View and in this case the Intent</li><li>Compulsary Usage of RxJava</li><li>Immutable objects</li></ul><h4>What should you use!</h4><p>Its completely up to you as you choice could be different according to your need and as MVP is more popular and has a good amount of documentation and tutorials online its easy to work with MVP and in the case of MVI it still don’t have a good documentation and lots of tutorials like MVP But If you are going with MVI the start with Mosby MVI as it offers the benefit that RxJava is already established in its library calls and a loose coupling between UI and business logic is inflicted.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98c143d1ee7c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-yoga/mvi-model-view-intent-pattern-in-android-98c143d1ee7c">MVI(Model-View-Intent) Pattern in Android</a> was originally published in <a href="https://medium.com/code-yoga">Code Yoga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Scripting Languages in Android]]></title>
            <link>https://medium.com/code-yoga/using-scripting-languages-in-android-developement-e9e37580d815?source=rss-979e15048193------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9e37580d815</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[scripting]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Tue, 13 Mar 2018 12:21:45 GMT</pubDate>
            <atom:updated>2018-04-06T05:58:12.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*5nICFHFXjnWh4VosWGQFJw.png" /></figure><p>At launch, Java was the only officially supported programming language for building distributable APK.Android Native Development Kit (Android NDK) which will allow developers to build Android software components with C and C++.In addition to delivering support for native code, Google is also extending Android to support popular <strong>dynamic scripting languages </strong>and<strong> </strong>Google launched the <a href="http://code.google.com/p/android-scripting/"><strong>Android Scripting Environment (ASE) </strong></a>but now it is Open Source and Known as <a href="https://github.com/damonkohler/sl4a">Scripting Layer for Android</a>(SL4A brings scripting languages to Android by allowing you to edit and execute scripts and interactive interpreters directly on the Android device.) and allows third-party developers to build simple Android applications with perl, JRuby, Python, LUA and BeanShell.SL4A makes it possible to quickly prototype applications for Android on the device itself using high-level scripting languages. These scripts have access to many of the APIs available to full-fledged Android applications, but with a greatly simplified interface and You can <a href="http://code.google.com/p/android-scripting/wiki/SharingScripts#Scripts_as_APKs">embed your script</a> in a stand alone APK.</p><p>You may ask, why write scripts instead of real Android applications? Admittedly, Android’s development environment makes life pretty easy, but you’re tied to a computer to do your work. ASE lets you develop on the device itself using high-level scripting languages to try out your idea now, in the situation where you need it, quickly. Have a look at the following example Lua script to see for yourself:</p><h4>Placing the phone face down will disable the ringer. Turning it face up again will enable the ringer.</h4><pre>require &quot;android&quot;<br>android.startSensing()<br>android.sleep(1)  --Give the sensors a moment to come online.<br>silent = false<br>while true do<br>  s = android.readSensors()<br>  facedown = s.result and s.result.zforce and s.result.zforce &gt; 9<br>  if facedown and not silent then<br>    android.vibrate()  --A short vibration to indicate we&#39;re in silent mode.<br>    android.setRingerSilent(true)<br>    silent = true<br>  elseif not facedown and silent then<br>    android.setRingerSilent(false)<br>    silent = false<br>  end<br>  android.sleep(1)<br>end</pre><h4>Here’s another useful script, this time in Python.</h4><p><strong>“Say chat messages aloud as they are received”</strong></p><pre>import android, xmpp<br><br>_SERVER = &#39;talk.google.com&#39;, 5223<br><br>class SayChat(object):<br>  def __init__(self):<br>    self.droid = android.Android()<br>    username = self.droid.getInput(&#39;Username&#39;)[&#39;result&#39;]<br>    password = self.droid.getInput(&#39;Password&#39;)[&#39;result&#39;]<br>    jid = xmpp.protocol.JID(username)<br>    self.client = xmpp.Client(jid.getDomain(), debug=[])<br>    self.client.connect(server=_SERVER)<br>    self.client.RegisterHandler(&#39;message&#39;, self.message_cb)<br>    if not self.client:<br>      print &#39;Connection failed!&#39;<br>      return<br>    auth = self.client.auth(jid.getNode(), password, &#39;botty&#39;)<br>    if not auth:<br>      print &#39;Authentication failed!&#39;<br>      return<br>    self.client.sendInitPresence()<br><br>  def message_cb(self, session, message):<br>    jid = xmpp.protocol.JID(message.getFrom())<br>    username = jid.getNode()<br>    text = message.getBody()<br>    self.droid.speak(&#39;%s says %s&#39; % (username, text))<br><br>  def run(self):<br>    try:<br>      while True:<br>        self.client.Process(1)<br>    except KeyboardInterrupt:<br>      pass<br><br>saychat = SayChat()<br>saychat.run()</pre><p>These scripts demonstrates several of the available APIs available for both <a href="http://code.google.com/p/android-scripting/wiki/LuaAndroidAPI">Lua</a> and <a href="http://code.google.com/p/android-scripting/wiki/PythonAndroidAPI">Python</a>. It is intended to be run as a service and silences the ringer when the phone is placed face down. For some scripting languages, like BeanShell, it’s possible to access Android’s Java API directly. To simplify things, ASE provides the AndroidFacade class. For other languages, like Python and Lua, the API is made available via <a href="http://json-rpc.org/">JSON RPC</a> calls to a proxy. Naturally this means that only the part of the API which has been wrapped by the AndroidFacade and AndroidProxy are available to cross-compiled interpreters like Python and Lua. Thankfully, both AndroidFacade and AndroidProxy are simple to extend.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9e37580d815" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-yoga/using-scripting-languages-in-android-developement-e9e37580d815">Using Scripting Languages in Android</a> was originally published in <a href="https://medium.com/code-yoga">Code Yoga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How AysncTask.java Works!]]></title>
            <link>https://medium.com/code-yoga/how-aysnctask-java-works-b3ca49c36c0d?source=rss-979e15048193------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3ca49c36c0d</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Shubham Soni]]></dc:creator>
            <pubDate>Fri, 09 Mar 2018 17:29:11 GMT</pubDate>
            <atom:updated>2018-04-06T04:59:03.403Z</atom:updated>
            <content:encoded><![CDATA[<p>In order to understand the inner working of AsyncTask.java we have to know about Half Sync/Half Async as AsyncTask is depended on it.</p><p><strong>What is Half Sync/Half Async ?</strong></p><p>The Half-Sync/Half-Async pattern decouples synchronous I/O from asynchronous I/O in a system to simplify concurrent programming effort without degrading execution efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/0*lQIuKfl8rLx19Piw." /></figure><h3>Applicability</h3><p>Use Half-Sync/Half-Async pattern when</p><ul><li>a system possesses following characteristics:</li><li>the system must perform tasks in response to external events that occur asynchronously, like hardware interrupts in OS</li><li>it is inefficient to dedicate separate thread of control to perform synchronous I/O for each external source of event</li><li>the higher level tasks in the system can be simplified significantly if I/O is performed synchronously.</li><li>one or more tasks in a system must run in a single thread of control, while other tasks may benefit from multi-threading.</li></ul><p>The way Asynctask has been implemented in Android, is an apt example of Half Sync — Half Async pattern described in Pattern Oriented Software Architecture or POSA2. First of all, let us try to understand what we mean by Half Sync-Half Async design pattern. Half Sync- Half Async pattern is a specific way how we want to structure our threads in a multithreaded application. As the name suggests, in this pattern we divide the solution of managing multiple threads into two different specific zones — one is synchronous and the other is an asynchronous zone. The main thread communicates with a thread asynchronously and this thread is responsible for queuing multiple tasks in a FIFO order. This thread then pushes these tasks on the synchronous layer to different threads taken from a thread pool. These thread pools then execute these tasks synchronously in the background.The whole process can be depicted by the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*5rPndq847DiQRgIa." /></figure><p>If you are new to the terms Asynchronous and Synchronous in the conjunction of multithreaded application let me throw some lights on it. These can be best understood in a client-server architecture perspective. A synchronous function means it will block the caller of it and will return only after it finishes its task. On the other hand an asynchronous function starts its task in the background but returns immediately to the caller. When it finishes the background task, it notifies the caller about it asynchronously and then the caller takes action.</p><p>The two scenarios have been depicted by the following two diagrams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*ccETXUmt3q0GKq0P." /></figure><p>Now let us dive deep into the Android’s Asynctask.java file to understand it from a designer’s perspective and how it has nicely implemented Half Sync-Half Async design pattern in it.</p><p><strong>In the beginning of the class few lines of codes are as follows:</strong></p><pre>private static final ThreadFactory sThreadFactory = new ThreadFactory() {</pre><pre>private final AtomicInteger mCount = new AtomicInteger(1);</pre><pre>   public Thread newThread(Runnable r) {<br>     return new Thread(r, “AsyncTask #” + mCount.getAndIncrement());<br>   }</pre><pre>  };</pre><pre>private static final BlockingQueue&lt;Runnable&gt; sPoolWorkQueue =new LinkedBlockingQueue&lt;Runnable&gt;(10);</pre><pre>/**</pre><pre>* An {@link Executor} that can be used to execute tasks in parallel.</pre><pre>*/</pre><pre>public static final Executor THREAD_POOL_EXECUTOR= new             ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);</pre><p>The first is a ThreadFactory which is responsible for creating worker threads. The member variable of this class is the number of threads created so far. The moment it creates a worker thread, this number gets increased by 1.</p><p>The next is the BlockingQueue. As you know from the Java blockingqueue documentation, it actually provides a thread safe synchronized queue implementing FIFO logic.</p><p>The next is a thread pool executor which is responsible for creating a pool of worker threads which can be taken as and when needed to execute different tasks.</p><p>If we look at the first few lines we will know that Android has limited the maximum number of threads to be 128 (as evident from private static final int MAXIMUM_POOL_SIZE = 128).</p><p>Now the next important class is SerialExecutor which has been defined as follows:</p><pre>private static class SerialExecutor implements Executor {</pre><pre>   final ArrayDeque&lt;Runnable&gt; mTasks = new ArrayDeque&lt;Runnable&gt;();<br>       Runnable mActive;</pre><pre>   public synchronized void execute(final Runnable r) {<br>     mTasks.offer(new Runnable() {<br>        public void run() {<br>          try {<br>            r.run();<br>          } finally {<br>              scheduleNext();<br>             }<br>         }<br>      });</pre><pre>     if (mActive == null) {<br>        scheduleNext();<br>      }</pre><pre>   }</pre><pre>  protected synchronized void scheduleNext() {<br>    if ((mActive = mTasks.poll()) != null) {<br>      THREAD_POOL_EXECUTOR.execute(mActive);<br>    }</pre><pre>  }</pre><pre>}</pre><p>The next important two functions in the Asynctask is</p><pre>public final AsyncTask&lt;Params, Progress, Result&gt; execute(Params… params) {<br>    return executeOnExecutor(sDefaultExecutor, params);<br>}</pre><p>and</p><pre>public final AsyncTask&lt;Params, Progress, Result&gt; executeOnExecutor(Executor exec,Params… params) {</pre><pre>     if (mStatus != Status.PENDING) {<br>       switch (mStatus) {<br>          case RUNNING:throw new IllegalStateException(“Cannot execute task:”+ “ the task is already running.”);</pre><pre>          case FINISHED:throw new IllegalStateException(“Cannot execute task:”+ “ the task has already been executed “+ “(a task can be executed only once)”);</pre><pre>     }</pre><pre>}</pre><pre>      mStatus = Status.RUNNING;<br>      onPreExecute();<br>      mWorker.mParams = params;<br>      exec.execute(mFuture);<br>      return this;</pre><pre>}</pre><p>AS it becomes clear from the above code we can call the executeOnExecutor from exec function of Asynctask and in that case it takes a default executor. If we dig into the sourcecode of Asynctask, we will find that this default executor is nothing but a serial executor, the code of which has been given above.</p><p>Now lets delve into the SerialExecutor class. In this class we have final</p><pre>ArrayDeque&lt;Runnable&gt; mTasks = new ArrayDeque&lt;Runnable&gt;();</pre><p>This actually works as a serializer of the different requests at different threads. This is an example of Half Sync Half Async pattern.</p><p>Now lets examine how the serial executor does this. Please have a look at the portion of the code of the SerialExecutor which is written as</p><pre>if (mActive == null) {<br>     scheduleNext();<br>}</pre><p>So when the execute is first called on the Asynctask, this code is executed on the main thread (as mActive will be initialized to NULL) and hence it will take us to the scheduleNext() function.</p><p>The ScheduleNext() function has been written as follows:</p><pre>protected synchronized void scheduleNext() {</pre><pre>     if ((mActive = mTasks.poll()) != null) {                             <br>           THREAD_POOL_EXECUTOR.execute(mActive);</pre><pre>     }<br>}</pre><p>So in the schedulenext() function we initialize the mActive with the Runnable object which we have already inserted at the end of the dequeue. This Runnable object (which is nothing but the mActive) then is executed on a thread taken from the threadpool. In that thread, then “finally “block gets executed.</p><p>Now there are two scenarios.</p><p>1. another Asynctask instance has been created and we call the execute method on it when the first task is being executed.</p><p>2. execute method is called for the second time on a same instance of the Asynctask when the first task is getting executed.</p><p>Scenario I : if we look at the execute function of the Serial Executor, we will find that we actually create a new runnable thread (Say thread t) for processing the background task.</p><p>Look at the following code snippet-</p><pre>public synchronized void execute(final Runnable r) {</pre><pre>     mTasks.offer(new Runnable() {<br>        public void run() {<br>          try {<br>            r.run();<br>          } finally {<br>            scheduleNext();<br>        }<br>    }<br>});</pre><p>As it becomes clear from the line mTasks.offer(new Runnable), every call to the execute function creates a new worker thread. Now probably you are able to find out the similarity between the Half Sync — Half Async pattern and the functioning of SerialExecutor. Let me, however, clarify the doubts. Just like the Half Sync — Half Async pattern’s Asynchronous layer, the</p><pre>mTasks.offer(new Runnable() {<br>     ….<br>}</pre><p>part of the code creates a new thread the moment execute function is called and push it to the queue (the mTasks). It is done absolutely asynchronously, as the moment it inserts the task in the queue, the function returns. And then background thread executes the task in a synchronous manner. So its similar to the Half Sync — Half Async pattern. Right?</p><p>Then inside that thread t, we run the run function of the mActive. But as it is in the try block, the finally will be executed only after the background task is finished in that thread. (Remember both try and finally are happening inside the context of t). Inside finally block, when we call the scheduleNext function, the mActive becomes NULL because we have already emptied the queue. However, if another instance of the same Asynctask is created and we call execute on them, the execute function of these Asynctask won’t be executed because of the synchronization keyword before execute and also because the SERIAL_EXECUTOR is a static instance (hence all the objects of the same class will share the same instance… its an example of class level locking) i mean no instance of the same Async class can preempt the background task that is running in thread t. and even if the thread is interrupted by some events, the finally block which again calls the scheduleNext() function will take care of it. what it all means that there will be only one active thread running the task. this thread may not be the same for different tasks, but only one thread at a time will execute the task. hence the later tasks will be executed one after another only when the first task complets. thats why it is called SerialExecutor.</p><p>Scenario II: In this case we will get an exception error. To understand why the execute function cannot be called more than once on the same Asynctask object, please have a look at the below code snippet taken from executorOnExecute function of Asynctask.java especially in the below mentioned portion:</p><pre>if (mStatus != Status.PENDING) {<br>   switch (mStatus) {<br>     case RUNNING:<br>        throw new IllegalStateException(“Cannot execute task:”+ “ the task is already running.”);<br>     case FINISHED:<br>          throw new IllegalStateException(“Cannot execute task:”+ “ the task has already been executed “+ “(a task can be executed only once)”);<br>     }</pre><pre>}</pre><p>AS from the above code snippet it becomes clear that if we call execute function twice when a task is in the running status it throws an IllegalStateException saying “Cannot execute task: the task is already running.”.</p><p>if we want multiple tasks to be executed parallely, we need to call the execOnExecutor passing Asynctask.THREAD_POOL_EXECUTOR (or maybe an user defined THREAD_POOL as the exec parameter.</p><p>Now its time for experimentation to justify whatever we have discussed so far is correct or not. Lets create an Android project. Make the minimum SDK version more than 12 say 14. And the target SDK version, say 17. Then lets make the two classes derived from Asynctask as follows.</p><pre>public class MyAsynctaskWithDelay extends AsyncTask&lt;String,Void,Void&gt; {<br>@Override</pre><pre>   protected Void doInBackground(String… arg0) {<br>     // TODO Auto-generated method stub<br>     System.out.println(arg0[0] + “before sleeping of        AsyctaskWithDelay..”);</pre><pre>    try {<br>      Thread.sleep(10000);<br>    } catch (InterruptedException e) {</pre><pre>       // TODO Auto-generated catch block<br>     e.printStackTrace();</pre><pre>     }</pre><pre>     System.out.println(arg0[0] + “after sleeping of AsyctaskWithDelay..”);</pre><pre>//System.out.println(arg0[0]);</pre><pre>     return null;</pre><pre>   }</pre><pre>}</pre><p>AND</p><pre>public class MyAsynctaskWithNoDelayLoop extends      <br>  AsyncTask&lt;String,Void,Void&gt; {<br>  @Override<br>  protected Void doInBackground(String… arg0) {<br>    // TODO Auto-generated method stub<br>    System.out.println(arg0[0] + “ The task with no delay…”);<br>    //System.out.println(arg0[0]);</pre><pre>    return null;</pre><pre>  }</pre><pre>}</pre><p>Now in the main Acivity class, add these following lines of code.</p><pre>MyAsynctaskWithDelay asynctask1 = new MyAsynctaskWithDelay();</pre><pre>MyAsynctaskWithDelay asynctask2 = new MyAsynctaskWithDelay();</pre><pre>MyAsynctaskWithNoDelayLoop asynctask3 = new MyAsynctaskWithNoDelayLoop();</pre><pre>MyAsynctaskWithNoDelayLoop asynctask4 = new MyAsynctaskWithNoDelayLoop();</pre><pre>asynctask1.execute(“Asynctask 1”);</pre><pre>asynctask2.execute(“Asynctask 2”);</pre><pre>asynctask3.execute(“Asynctask 3”);</pre><pre>asynctask4.execute(“Asynctask 4”);</pre><p>Now if we run this application we will find that tasks are executing serially. And the output will be like the following:</p><pre>9–03 11:45:06.521: I/System.out(784): Asynctask 1before sleeping of AsyctaskWithDelay..</pre><pre>9–03 11:45:16.532: I/System.out(784): Asynctask 1after sleeping of AsyctaskWithDelay..</pre><pre>9–03 11:45:16.594: I/System.out(784): Asynctask 2before sleeping of AsyctaskWithDelay..</pre><pre>9–03 11:45:26.603: I/System.out(784): Asynctask 2after sleeping of AsyctaskWithDelay..</pre><pre>9–03 11:45:26.612: I/System.out(784): Asynctask 3 The task with no delay…</pre><pre>9–03 11:45:26.615: I/System.out(784): Asynctask 4 The task with no delay…</pre><p>As you see from the output, the tasks are being executed in accordance to the sequence of their calling of execute() function.</p><p><a href="https://www.dre.vanderbilt.edu/~schmidt/cs282/PDFs/6-Concurrency-and-Synchronization-part10.pdf">Read More About Half Sync/Half Async design Pattern</a></p><p><a href="https://www.scribd.com/document/28282356/Half-Sync-Half-Async">Architecture of Half sync/Half Async Pattern By Douglas C.Schmidt and Charles D. Cranor</a></p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3ca49c36c0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-yoga/how-aysnctask-java-works-b3ca49c36c0d">How AysncTask.java Works!</a> was originally published in <a href="https://medium.com/code-yoga">Code Yoga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>