<?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 Mohamed Ibrahim on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Ibrahim on Medium]]></description>
        <link>https://medium.com/@mibrahimdev?source=rss-865ef9ea000d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Hf8jjwA7Vi9Qsu0Sx6q-Zg@2x.jpeg</url>
            <title>Stories by Mohamed Ibrahim on Medium</title>
            <link>https://medium.com/@mibrahimdev?source=rss-865ef9ea000d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:42:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mibrahimdev/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[How to be so good that they can’t ignore you? The Software Engineering version]]></title>
            <link>https://levelup.gitconnected.com/how-to-be-good-they-cant-ignore-you-the-software-engineering-version-ed80a53a0bdb?source=rss-865ef9ea000d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed80a53a0bdb</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mohamed Ibrahim]]></dc:creator>
            <pubDate>Wed, 11 Aug 2021 14:22:22 GMT</pubDate>
            <atom:updated>2021-10-08T07:28:30.273Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhsJIOo3n2zjo-N4x3ufpA.jpeg" /><figcaption><a href="https://unsplash.com/photos/0g-iLtxmMhA">Unsplash</a></figcaption></figure><p>Lately, we’ve started to discuss various topics related to Android, Clean Architecture, Unit Testing, Rx and more. So feel free to join us at the <a href="https://www.clubhouse.com/club/nerddroid">NerdDroid</a> club at Clubhouse.</p><p>The last discussion was about how to stand out from the crowd; Software development is still growing and catching a lot of interest from individuals who’re seeking a flexible and high paid career.</p><p>At some point, you’ll hit this peak where you’re not enjoying what you do. You will miss this feeling of writing your first Hello world, learning how to write simple programs.</p><p>As we advance in our development career, you will write a couple of apps and learn some patterns that will make you survive; if you’re lucky or have the passion for learning, you will touch SOLID and clean code topics, Design patterns, and other advanced topics.</p><p>In addition to that, there are rapid changes in the development stack. Everything is changing; many things are deprecated, even the <a href="https://www.reddit.com/r/mAndroidDev/comments/lr1w8s/deprecated_is_now_deprecated/gok7tv1/">deprecated annotation</a> itself has been deprecated. Who can imagine!.</p><p><strong>So what’s next?</strong></p><p>At this point, everyone is doing what you’re doing, you’re trying to catch the running stack changes, but you can’t. You’re already can develop any app with what you have learned.</p><p>Here are some essential points We’ve discussed, and we think it could help you be good that they can’t ignore your talent and skills.</p><h3>Read Documentation</h3><p>Sorry that we’ve started with the boring stuff, but this is a crucial skill you must develop; many entry and mid-level developers and sometimes the experienced ones skip documentation in favor of Stackoverflow.</p><p>Documentation is written to guide you on using code, what you should/shouldn’t do, and what errors this function throws. Yes, it depends on its quality, but it should be your starting point.</p><p>And the argument here is so simple: if you have a bug related to some code, not yours, and you are just using it. It is so practical to read what the owner wrote about in the documentation.</p><h3>Expand your stack</h3><p>If you’re considering yourself as a software engineer, It’s recommended to touch different stacks and tools. Expanding your stack will give you a broader picture, so don’t tighten yourself with just one technology or a framework. But make sure you have mastered one.</p><p>If you’re an Android developer, it’s good to know about Flutter; if you’re a cross-platform developer, it’s good to touch the native world. It increases the communication level with other developers, and You could learn some patterns to use in your original stack.</p><p>For example, the declarative UI initiative started with React native. Now you can find it everywhere.</p><h3>Learn Data structure and Algorithms</h3><p>If you’re in the development industry, you may not touch so many Data structures or Algorithms. Many of it it’s already implemented in the language or the library, or in the SDK you use. But we can summarize the importance of studying Data structures and Algorithms in two points.</p><ul><li>Understanding the code you use.</li><li>The ability to design and write high performant code.</li></ul><p>If you don’t want to achieve those, don’t study them, some of you would suggest adding a third point which is being prepared for interviews. But this is not the case. I think that intention itself could lead you to memorize problems and skim this vital part of our jobs.</p><h3>Write Clean, Testable code.</h3><p>The purpose of communicating with a computer is to solve a problem. The purpose of communicating with your peers is to iterate faster, attaining high-quality deliverable products.</p><p>You could find the later purpose between the Agile manifesto words, change code with a validation, Is what testing does, debugging code without asking the code owner what this piece of code does is what clean code should accomplish.</p><p>If you have the skill to write clean code with tests, you’d be a more valuable developer and will play well with others.</p><h3>The Product Owner Mindset</h3><p>We as developers tend to care more about the languages, syntax, tools, and framework than the domain or what businesses want to achieve. And it’s understandable we’re are the tech guys, but finding the right solution depends on the first place of understanding the problem.</p><p>If you do not understand the big picture of the business you’re working on, then you could cause some issues that are not related to code by any means. Unfortunately, those issues are most challenging to discover.</p><p>So if you really want to stand out, care more about the domain problems you want to solve in your daily work.</p><h3>Automate things</h3><p>Some of the simplest tasks we do, take much more time than we think. If it’s repeatable, then automate it. The whole CI/CD depends on that idea. Hence try to find tasks in your daily work that you always do and automate it.</p><p>Automating repeated tasks makes you focus on what matters, like writing Unit tests for your code. In this case, you might want to learn a scripting language like Ruby.</p><h3>Belong to a community or Build one</h3><p>I think the community is one of the critical factors in any career progress I had. I remember learning MVP, RX, Clean architecture back then just because I was checking <a href="https://www.reddit.com/r/androiddev/"><strong>r/androiddev</strong></a> regularly.</p><p>Being valuable to the community, sharing your findings, contributing to open source is the best that you can do in your free time to advance your development career.</p><p>If for example, you’re reading an open-source code and can’t understand it, you’ll find the urge to search for it and learn about it. Asking in <a href="https://kotlinlang.slack.com/"><strong>Kotlin slack channel</strong></a>, stack overflow, or even Twitter is all that makes learning software development an enjoyable experience.</p><p><em>Learn, develop and share knowledge.</em></p><h3>The Soft Skills</h3><p>It doesn’t matter how smart you are if you can’t communicate well with your team or managers. Sometimes you will find some decisions that are not tech-wise, sometimes you will have situations when there’re PRs conflicts and a slow process.</p><p>It’s normal to experience all of that. The fun fact is that it’s part of the job, but the critical thing here is how to deal with the situation with a win-win attitude.</p><p>As a start, you have to put the effort to listen and understand others. One of the key insights is to learn about the differences between cultures; how to communicate well with them.</p><p>The Culture map book is excellent, to begin with, and You had Mustafa Nagib summarised it for you <a href="https://www.youtube.com/watch?v=RNAPDWd5Zy0"><strong>here</strong></a>.</p><h3>Keep an eye on your gaps</h3><p>Some of the mentioned points might not apply to you. Therefore no one knows what you miss more than you. You could be lucky working with a team leader who could guide you to the right track. or in a cooperative environment, And I think any developer has to seek such an environment where he can grow.</p><p>But let’s say you’re a lone wolf, or you’re at some point of your career where you don’t have this heavenly development environment, or even like many learners today, you’re not a CS major. Then you have two things to do</p><ul><li>Belong to a community.</li><li>Keep track of your gaps</li></ul><p>We’ve talked about the community, But what about your learning or what’s the next thing you should learn, you could find some public roadmaps, for example, this one for <a href="https://trello.com/b/fsc44tYh/android-developer-roadmap"><strong>Android</strong></a>, and even if you want to learn CS from scratch, you could pick courses from this <a href="https://github.com/ossu/computer-science"><strong>curriculum</strong></a> from a time to another.</p><h3>Learn how to learn?</h3><p>Our job includes a lot of Reading, research, design, making decisions. We could optimize those if we’ve learned how our brain works and retrieve a lot of our learning findings. So what is the best way to learn?</p><p>keep an eye on what works for you, some prefer tech talks, some favorite books, some love to discuss with others, it doesn’t matter, we have our differences, so your job is to find the best for you.</p><p>Mentioning that, Reading could be an exception because you’ll have to read code, documentation, articles, deep-dive books, all of that requires sufficient reading skill.</p><p><strong>In the end, </strong>Those points are what we’ve discussed for 3 hours. Sure it could be more than these, if you have a suggestion, you’re welcome to leave it in the comments, and we’ll make sure to pick and discuss them in the incoming rooms.</p><p>&gt;&gt; leaving quietly ✌🏻</p><p>— — — — — — —</p><p><em>Special thanks to room moderators who helped me to shape this article:</em></p><p><em>Mina Rezkalla - Ahmed Adel - Amr AlMadah - Ammer - Ahmed Mussa - Ahmed Khalil</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed80a53a0bdb" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-be-good-they-cant-ignore-you-the-software-engineering-version-ed80a53a0bdb">How to be so good that they can’t ignore you? The Software Engineering version</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flow: an intro for an RxJava user]]></title>
            <link>https://medium.com/swlh/flow-an-intro-for-an-rxjava-user-1b5b6eb21790?source=rss-865ef9ea000d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b5b6eb21790</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[rxandroid]]></category>
            <category><![CDATA[flow]]></category>
            <dc:creator><![CDATA[Mohamed Ibrahim]]></dc:creator>
            <pubDate>Tue, 10 Mar 2020 13:07:07 GMT</pubDate>
            <atom:updated>2020-03-13T15:28:34.565Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*1OiDWqlEhgoImdpMbyC1Zg.png" /><figcaption>image credit: <a href="https://unsplash.com/photos/Bd7gNnWJBkU">https://unsplash.com/photos/Bd7gNnWJBkU</a></figcaption></figure><p>RxJava may be the most important library I learned to use, Rx in general is a different paradigm to write code, Kotlin as a new programming language give it a shot for implementing Flow powered by coroutines as an Rx implementation of its own. I may introduced Coroutines in <a href="https://medium.com/@MohamedISoliman/hello-kotlin-coroutines-4e40cb9a106c?source=---------2------------------">Hello Kotlin Coroutines</a>, and that was necessary to understand Flow.</p><p>Kotlin has as set of extensions to facilitate working with collections. but it’s not considered as reactive.</p><pre>listOf(&quot;Madara&quot;, &quot;Kakashi&quot;, &quot;Naruto&quot;, &quot;Jiraya&quot;, &quot;Itachi&quot;)<br>    .map { it.length }<br>    .filter { it &gt; 4 }<br>    .forEach {<br>        println(it)<br>    }</pre><p>In this example if you dig deep in map function source code, you will find no magic, it is just a loop over the list, doing some transformation then give you a new list. filter do the same. this mechanism called an eager evaluation, where the function do its operation over the whole list and give you a new list. but what if we don’t need to create those intermediate lists, and we need to save some memory, then we could use <a href="https://kotlinlang.org/docs/reference/sequences.html"><strong><em>Sequences</em></strong></a>.</p><pre>listOf(&quot;Madara&quot;, &quot;Kakashi&quot;, &quot;Naruto&quot;, &quot;Jiraya&quot;, &quot;Itachi&quot;)<br>    .asSequence()<br>    .map { it.length }<br>    .filter { it &gt; 4 }<br>    .forEach {<br>        println(it)<br>    }</pre><p>The only difference here that we convert our list to a sequence, then apply our operations, after navigating to map function again, we find something different, it’s just a decorator for the sequence, the return type is also a sequence. with <strong><em>Sequence</em></strong> map only operate on items one by one, and any other operator we apply like filter. with large lists Sequences is much better than normal collections, and it only will run lazily, <strong><em>Sequence </em></strong>do its job synchronously, Is there a way to use those transformation operators asynchronous. here it comes Flow.</p><h3>Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vRo_Td2MTHufyipKeYNRA.png" /></figure><p>If we tried to take our list and use it as flow, calling <strong><em>collect{..} </em></strong>at the end of the stream, we will get a compile error. And the reason that Flow is built on Coroutines, it has the asynchronous capabilities by default, so you could just use it as you use <a href="https://medium.com/@MohamedISoliman/hello-kotlin-coroutines-4e40cb9a106c">coroutines</a> in your code.</p><p><strong><em>Collect{…}</em></strong> operator is terminal operator where you get the emissions, you could think of it like <strong><em>subscribe</em></strong> in Rxjava.</p><p>Flow is also cold stream, and that means, your flow will not be executed until you call a terminal operator on it, like <strong><em>collect()</em></strong>. and if you collect more than once, each time you will get the same emissions.</p><p>So Collections extension functions is only friendly in small data, sequences could save you some unnecessary work, and with Flow you write code reactively with the power of coroutines. So let’s learn how to build it…</p><h3>Flow builders</h3><p>We have seen <strong><em>asFlow()</em></strong><em> </em>which is an extension function on Collections to convert it to flow, navigating to source code:</p><pre>public fun &lt;T&gt; Iterable&lt;T&gt;.asFlow(): Flow&lt;T&gt; = flow {<br>    forEach { value -&gt;<br>        emit(value)<br>    }<br>}</pre><p><strong><em>flow {…}</em></strong> is the main flow builder with the function <em>emit(), </em>if we want to write our previous example to add some logic in the data source, or imitate the source behavior we simply use <strong><em>flow {…}</em></strong>. and we also have <strong><em>flowof()</em></strong>.</p><h3>Operators</h3><p>Flow has a set of operators to apply transformation on emissions, like map, filter, groupBy, scan .. and many others, they’re all cold.</p><p>In RxJava you may hit this question once at least, what is the difference between map and flatMap and the closest answer you may get, <a href="https://youtu.be/QdmkXL7XikQ?t=603">is when you have a list of a list and you want to get all the items emitted one by one</a>, that’s the simplified answer of <strong><em>flatMap() vs map() </em></strong>and it’s correct but the other point with <strong><em>map() </em></strong>is you do synchronous mapping, and the solution to do it asynchronously is to use <strong><em>flatMap() </em></strong>because map doesn’t support that.</p><p>In Flow powered by Coroutines, you could use asynchronous code in your operators naturally, let’s assume we want to do some mapping logic that take some time, we represent that by just delaying one second. with RxJava you would use flatmap with applying some logic on it .. it may seem like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCCWbfpOWplvIWDBqKMnOA.png" /></figure><p>The argument here is Flow has a simple design, and easy to learn comparing with RxJava which is known of its steep learning curve, I’ll just put this image here to make it short.</p><p>With Flow…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nVeYDz5HBbFT9YmjluFjw.png" /></figure><h3>Terminal operators</h3><p>I have mentioned that <strong><em>collect()</em></strong><em> </em>is a terminal operator, and by terminal I mean that you get the result when you call it, in RxJava with cold streams, you start it by calling <strong><em>subscribe()</em></strong>, or if you want it in a blocking way, you call <strong><em>blockingGet()</em></strong>.</p><p>Terminal operators in Flow, are suspend functions which need a scope to operate on, some other terminal operators will be</p><ul><li><strong><em>toList()</em></strong>,<strong><em> toSet</em></strong> -&gt; return all items in a collection.</li><li><strong><em>first()</em></strong> -&gt; return the first emission only.</li><li><strong><em>reduce()</em></strong>,<strong><em> fold()</em></strong> -&gt; accumulate emissions with a specific operation</li></ul><h3>Launching</h3><p>To make flow start emitting, you need to launch it as any suspend function, So the pattern to start your flow will be…</p><pre>//fire a coroutine<br>someScope.launch {</pre><pre>  //fire flow with a terminal operator<br>  flowSampleData().collect { }</pre><pre>}</pre><p>The curly braces remind me of callbacks, a nice thing to do is replace it with <strong><em>launchIn()</em></strong>, but how we handle our emissions, for that you use <strong><em>onEach{…}</em></strong></p><pre>flowSampleData()<br>    .onEach {</pre><pre>     //handle emissions<br>     <br>    }<br> <br>     .launchIn(someScope)</pre><h3>Cancellation</h3><p>Each time we setup RxJava subscription, we had to care about clearing those subscriptions to avoid memory leaks or an expired task working in background, RxJava support that by giving you a reference to the subscription as <strong><em>disposable()</em></strong> and you usually call <strong><em>disposable().dispose() </em></strong>in your component exit point, if you have more than one you collect those in <strong><em>CompositeDisposable() </em></strong>then you call <strong><em>clear()</em></strong> or <strong><em>dispose()</em></strong>.</p><p>with the Coroutine scope setup you don’t need any additional work, structured concurrency fill that purpose.</p><h3>Errors</h3><p>One of the most useful features of RxJava is the way you handle errors, you have this <strong><em>onError() </em></strong>function which catch any error in the stream. Flow has a similar one called <strong><em>catch{…} </em></strong>and without using catch{…} you’re code may throw an exception or your app crash. and by this you the choice to code with regular try catch or in declarative way using <strong><em>catch{…}</em>. </strong>let’s mock a source with error</p><pre>private fun flowOfAnimeCharacters() = flow {<br>    emit(&quot;Madara&quot;)<br>    emit(&quot;Kakashi&quot;)</pre><pre>    //throwing some error<br>    throw IllegalStateException()</pre><pre>    emit(&quot;Jiraya&quot;)<br>    emit(&quot;Itachi&quot;)<br>    emit(&quot;Naruto&quot;)<br>}</pre><p>and the consumer code ..</p><pre>runBlocking {</pre><pre>    flowOfAnimeCharacters()<br>        .map { stringToLength(it) }<br>        .filter { it &gt; 4 }<br>        .collect {<br>            println(it)<br>        }<br>}</pre><p>if we run this code it will throw an exception, and as we said you have two options to handle errors, the regular try-catch and <strong><em>catch{…}</em></strong>. here is the modified code in both cases.</p><pre>// using try-catch<br>runBlocking {<br>    try {<br>        flowOfAnimeCharacters()<br>            .map { stringToLength(it) }<br>            .filter { it &gt; 4 }<br>            .collect {<br>                println(it)<br>            }<br>    } catch (e: Exception) {<br>        println(e.stackTrace)<br>    } finally {<br>        println(&quot;Beat it&quot;)<br>    }<br>}</pre><p>Using catch{…}</p><pre>runBlocking {<br>    flowOfAnimeCharacters()<br>        .map { stringToLength(it) }<br>        .filter { it &gt; 4 }<br>        .catch { println(it) }<br>        .collect {<br>            println(it)<br>        }<br>}</pre><p>There’s something happens with second option, it’s important to order the catch operator just down the stream before the terminal operator, so you could catch all errors if that what you want.</p><h3>Resuming</h3><p>If error break the stream and our intention to resume it with fullback or default data, we used to have <strong><em>onErrorResumeNext()</em></strong> or <strong><em>onErrorReturn()</em></strong> in Rxjava, in Flow we also use <strong><em>catch{…}</em></strong> but we call <strong><em>emit() </em></strong>inside of it to produce backup emissions one by one, or even better we could introduce a whole new flow with <strong><em>emitAll()</em></strong> like we did, if our heroes didn’t make it to the battleground, we need “Minato” and “Hashirama”.</p><pre>runBlocking {<br>    flowOfAnimeCharacters()<br>        .catch {<br>            emitAll(flowOf(&quot;Minato&quot;, &quot;Hashirama&quot;))<br>        }<br>        .collect {<br>            println(it)<br>        }<br>}</pre><p>And that will get us</p><pre>Madara<br>Kakashi<br>Minato<br>Hashirama</pre><p>See, no new operators :”)</p><h3>flowOn()</h3><p>Flow data source by default will run in the caller context, if you want to change that and for example you want flow source to run on IO instead of Main we use <strong><em>flowOn() </em></strong>for that, and change context for the upstream, upstream is all the operators before calling flowOn. here’s a nice doc example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jcPldPvBZgboAnycMU2TEQ.png" /></figure><p><strong><em>flowOn()</em></strong> here is acting for both its equivalent in RxJava [subscribeOn() — observeOn()], you write your stream then you decide which context will operate on.</p><h3>Completion</h3><p>You may need to do something when Flow is done emitting, for that you have <strong><em>onCompletion{…}</em></strong>, and it determine whether the flow collection was completed normally or exceptionally. let’s use it in our anime characters example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2PwSRiSdjlw6L1wzc3N5A.png" /></figure><p>Give it a minute to guess the result, knowing that the data source is</p><pre>private fun flowOfAnimeCharacters() = flow {<br>    emit(&quot;Madara&quot;)<br>    emit(&quot;Kakashi&quot;)<br>    throw IllegalStateException()<br>    emit(&quot;Jiraya&quot;)<br>    emit(&quot;Itachi&quot;)<br>    emit(&quot;Naruto&quot;)<br>}</pre><p><strong><em>Catch{…}</em></strong> will do it’s job catching the <em>IllegalStateException() </em>and resuming with the new flow<em>, </em>that leave us with “Madara”, “Kakashi” from the source and with “Minato”, “Hashirama” from the fullback flow. but what about <strong><em>onCompletion{…}</em></strong>, does it print the error?!</p><p>The answer is No, catch caught all the errors, and what come next is a whole new thing, put in mind that <strong><em>onCompletion{…}</em></strong> and <strong><em>catch{…}</em></strong> are just mediator operators. their order really matters.</p><p><strong><em>Let’s recap what we achieved until now…</em></strong></p><p><em>You build a flow using Flow builders, the most basic one is </em><strong><em>flow{…}</em></strong><em>. if you want to start the flow, you call a terminal operator like </em><strong><em>collect{…} </em></strong><em>and because terminal operators are suspend functions, you need a scope with the coroutine builder </em><strong><em>launch{…} </em></strong><em>or if you want to do it in an elegant style, you use </em><strong><em>launchIn() </em></strong><em>combined with </em><strong><em>onEach{…}</em></strong><em>. Use </em><strong><em>catch{…} </em></strong><em>to catch the upstream errors, and provide it with a fallback flow if you want to. </em><strong><em>onCompletion{..} </em></strong><em>will trigger after upstream done all emission or when error happens. all that will work on the caller coroutine context by default, if you want to change the upstream context, you use </em><strong><em>flowOn()</em></strong><em>.</em></p><p>I hope you enjoyed this little intro about flow, I’ll try to write more about it and to discover its place app architecure, until that happy flowing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b5b6eb21790" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/flow-an-intro-for-an-rxjava-user-1b5b6eb21790">Flow: an intro for an RxJava user</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello Kotlin Coroutines]]></title>
            <link>https://medium.com/swlh/hello-kotlin-coroutines-4e40cb9a106c?source=rss-865ef9ea000d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e40cb9a106c</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Mohamed Ibrahim]]></dc:creator>
            <pubDate>Wed, 19 Feb 2020 15:37:45 GMT</pubDate>
            <atom:updated>2020-02-19T15:49:22.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*doBVFIq8s0wZO6LZGq1C9w.jpeg" /><figcaption>image credit: <a href="https://unsplash.com/photos/Bd7gNnWJBkU">https://unsplash.com/photos/Bd7gNnWJBkU</a></figcaption></figure><p>Any UI framework has its own main thread to do the rendering and observing touch events, this thread by all means is the most important thread you should care of. User will never know if you wrote your code with AsynckTask or a Coroutine, but he will feel the responsiveness of the App. so organizing the tasks that your code does is an important part you should be aware of.</p><h3>Hello from the Async side</h3><p>If you have an expensive api call, it must not happen in the main thread, Android for example will crash your app if you’ve done that. so one solution is to fire this api call in a background thread and get the result in a callback. or you could use Rxjava Observable, or now you can use <strong><em>coroutines</em></strong>.</p><p>coroutines are similar to threads, but they’re more efficient in the way of using resources. you could have many coroutines as you want. Coroutines literally means cooperative functions, but what does that mean?</p><p>Well in normal functions, you could call function inside another, and the execution will be done line by line, so for example due to the below code, what will happen when you call funA in main?</p><pre>fun main() {<br>    funA()</pre><pre>}</pre><pre>fun funA() {<br>    println(&quot;start....&quot;)<br>    funB()<br>    funC()<br>    println(&quot;......end&quot;)<br>}</pre><pre>fun funB() {<br>    println(&quot;Hello&quot;)<br>}</pre><pre>fun funC() {<br>    println(&quot;World!&quot;)<br>}</pre><p>it may look like a ridiculous question, we do programming for while now, but bear with me, the execution in that case will go line by line, every time it hits another function call, will go to execute its code, then get back to continue lines after this second function and so on.</p><p>let’s make it little bit complex, what if funB and funA take some time to do their jobs, imagine that those simple strings come from network or a DB. and we will mock that by just delaying their response.</p><pre>fun main() {<br>    val timeMillis = measureTimeMillis {<br>        funA()<br>    }<br>    println(timeMillis)<br>    println(&quot;Exiting main...&quot;)</pre><pre>}<br></pre><pre>fun funA() {<br>    println(&quot;start....&quot;)<br>    funB()<br>    funC()<br>    println(&quot;......end&quot;)<br>}</pre><pre>fun funB() {<br>    Thread.sleep(1000)<br>    println(&quot;Hello&quot;)<br>}</pre><pre>fun funC() {<br>    Thread.sleep(1000)<br>    println(&quot;World!&quot;)<br>}</pre><p>Can you expect the result?</p><pre>start....<br>Hello<br>World!<br>......end<br>2011<br>Exiting main...</pre><p>if you run this code, it will print first line instantly, wait one sec, print Hello, wait for another second, print World! and print execution time, then exiting program.</p><p>so it took almost two seconds, to be done. but Could we optimize this code to do it in one second?</p><p>and here it comes the idea of using Concurrency, you could use threads to minimize the time of your app execution. by dividing the heavy work between them, and there’s already a set of tools supported in Java to help you achieving that, but to make it short, let’s enhance our app performance using Threads.</p><pre>fun funA() {<br>    println(&quot;start....&quot;)<br>    thread { funB() }<br>    thread { funC() }<br>    println(&quot;......end&quot;)<br>}</pre><p>and we will add a small change to the main function by blocking main thread for around one second</p><pre>fun main() {<br>    val timeMillis = measureTimeMillis {<br>        funA()<br>        Thread.sleep(1300) //blocking main<br>    }<br>    println(timeMillis)<br>    println(&quot;Exiting main...&quot;)<br>}</pre><p>now app result will be like this</p><pre>start....<br>......end<br>Hello<br>World!<br>1311</pre><pre>Exiting main...</pre><p>So we achieved doing our heavy work in half the time using Threads, but we have to say this, Threading require a lot of knowledge to write predictive bug free concurrent app. and the other thing, they are very expensive, you could run out of memory if you overused them.</p><p>So it came to those two points, <strong><em>Syntax</em></strong> and <strong><em>Resources</em></strong>,<strong><em> </em></strong>in a perfect world you would write your imperative/sequential code without changing anything and you<em> </em>would be safe of out of memory situations.</p><p>Koltlin as a new language, it has this concept of design where want you to to use your daily programming skills, like regular imperative synchronous code, try-catch to handle errors, So they introduced coroutines for that reason. so your old synchronous code can be easy with minimal changes turned into an asynchronous one.</p><h3>Coroutines</h3><p>Threads are runtime solution, you just grab a thread from the JVM to do your heavy work. on the other hand Coroutines are the compiletime solution, where a new mechanism being introduced to the compiler making functions (rotuines) able to cooperate (Co).</p><p><strong><em>suspend</em></strong> functions is where the caller function at our example funA, just start the execution of funB, we could say funA just suspended the continuation of funB untill B finish its job.</p><p>the confusion part here that this may look exactly the same when we introduced threads. the one key difference that you don’t need to use many threads here, Coroutine is just cheap to use, how this look like with our example .. let’s convert it.</p><pre>fun main() {<br>    val job = GlobalScope.launch {<br>        funA()<br>    }<br>    Thread.sleep(2300)<br>    println(&quot;Exiting main...&quot;)<br>}</pre><pre>suspend fun funA() {<br>    println(&quot;start....&quot;)<br>    funB()<br>    funC()<br>    println(&quot;......end&quot;)<br>}</pre><pre>suspend fun funB() {<br>    delay(1000)<br>    println(&quot;Hello&quot;)<br>}</pre><pre>suspend fun funC() {<br>    delay(1000)<br>    println(&quot;World!&quot;)<br>}</pre><p>There’s couple of changes here, let’s start with A,B,C functions, first of all they’re all marked with <strong><em>suspend</em></strong> keyword, second we replaced <strong><em>Thread.sleep()</em></strong><em> </em>with<em> </em><strong><em>delay() </em></strong>which is a helper function to delay execution in Coroutines.</p><p>In main function we use<strong><em> GlobalScope.launch </em></strong>which is a Coroutine builder to start executing our code. if you run that code you will get result nearly same as the first one, where we didn’t introduce any concurrent tools. and it will take around two seconds to finish. and a second look at the code, you can see that changing <strong><em>synchronous</em></strong> code to an <strong><em>asynchronous</em></strong> is not that hard with coroutines compared to Threads. but could we optimize our code so it take just half the time to be done?</p><h3>Parallelism</h3><p>let’s change our code so funB and funC return data, and the printing occur in funA</p><pre>fun main() {<br>    GlobalScope.launch {<br>        val millisCoroutine = measureTimeMillisCoroutine { funA() }<br>        println(&quot;Took $millisCoroutine&quot;)<br>    }<br>    Thread.sleep(2300)<br>    println(&quot;Exiting main...&quot;)<br>}</pre><pre>suspend fun funA() {<br>    println(&quot;start....&quot;)<br>    println(&quot;$funB() $funC()&quot;)<br>    println(&quot;......end&quot;)<br>}</pre><pre>suspend fun funB(): String {<br>    delay(1000)<br>    return &quot;Hello&quot;<br>}</pre><pre>suspend fun funC(): String {<br>    delay(1000)<br>    return &quot;World!&quot;<br>}</pre><p>It took almost same time, around 2 seconds to finish, to solve that we could use <strong><em>Async</em></strong> and <strong><em>Await</em></strong>, excuse me what are those?</p><p>Those are coroutine builders which enable parallel execution, you just wrap your function with <strong><em>async {}</em></strong> and it return a <strong><em>Defferred&lt;T&gt;</em></strong> which is simply a future or a promise that you’ll get the desired value.</p><p>let’s modify our example</p><pre>suspend fun funA() {<br>    println(&quot;start....&quot;)</pre><pre>    val helloDeffered = GlobalScope.async { funB() }</pre><pre>    val worldDeffered = GlobalScope.async { funC() }</pre><pre>    println(&quot;${helloDeffered.await()} ${worldDeffered.await()}&quot;)</pre><pre>    println(&quot;......end&quot;)<br>}</pre><p>if you run this code it will get you the result</p><pre>start....<br>Hello World!<br>......end<br>Took 1018</pre><pre>Exiting main...</pre><p>So our coroutines now run in a parallel modes.</p><h3>Structured Concurrency</h3><p>Whether you use the regular callback or the futures, or Rxjava observables, those concurrent setups has to be cleared when Activity is destroyed, so it doesn’t leak memory. if you’re familiar with <a href="https://github.com/uber/AutoDispose">autodispose</a> it’s a library to clear <strong><em>Rxjava</em></strong> subscriptions when the component is being destroyed. so you don’t have to clear it yourself making a bag of disposables and clear it in <strong><em>onDestroy</em></strong>.</p><p>Coroutine has this concept of “<strong><em>Structured concurrency</em></strong>”, it may seem a big term, or totally new to us, but it solves the previous problem, Strucured concurrency is all about defining some standards so concurrent programs has clear entry and exit points.</p><h3>Coroutine Scope</h3><p>one of those rules structured concurrency apply is you don’t launch coroutines without a coroutine scope, in our example we used <strong><em>GlobaleScope</em></strong> which a specific type of scope, basicly means the scope of the app.</p><p>in Android the newer ViewModel has its own new scope, which you can use, so you don’t have to setup the scoping code yourself.</p><p>but if you want to do it yourself, in Activity for example, all you have to do is to implement Coroutine scope in your runner class and define the context.</p><pre>class WelcomingScreen : Activity, CoroutineScope by CoroutineScope(Dispatchers.Default) {</pre><pre>}</pre><p>if we moved our example to this Android app, you can now get rid of GlobalScope, because the new scope now is tied to the Activity lifecycle.</p><h3>Coroutine Context</h3><p>any coroutine scope require a context, A context is a set of elements, one of those elements is the worker thread that will be used to be execute coroutines, it’s called in Coroutines terms <strong><em>Dispatchers</em></strong>.</p><p>If you defined a parent scope with default dispatcher, all childeren coroutines will inherit this context. unless you pass new context to the later launch/withContext function, and this how you switch between threads.</p><p>So let’s return to our WelcomeScreen example, we now want to do the async calls in IO dispatcher, you can pass the Dispatcher type in async. we use <strong><em>withContext()</em></strong> passing the main dispatcher to get result in main thread (UI). how this will look like. let’s first modify our code so funA return the whole string we want to print.</p><pre>suspend fun funA(): String {<br>    println(&quot;start....&quot;)</pre><pre>    val helloDeffered = async(Dispatchers.IO) { funB() }<br>    val worldDeffered = async(Dispatchers.IO) { funC() }</pre><pre>    println(&quot;......end&quot;)</pre><pre>    return helloDeffered.await() + &quot; &quot; + worldDeffered.await()</pre><pre>}</pre><p>Let’s continue with our Android example, we will modify our code in onCreate so it execute funA in IO and printing the returned value in the UI thread.</p><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)</pre><pre>    setContentView(R.layout.activity_main)</pre><pre>    launch {<br>        println(&quot;Launch Thread: ${Thread.currentThread().name}&quot;)</pre><pre>        val string = funA()</pre><pre>        println(&quot;Logging Thread: ${Thread.currentThread().name}&quot;)</pre><pre>        withContext(Dispatchers.Main) {<br>            Toast.makeText(<br>                this@WelcomeScreen, string,Toast.LENGTH_LONG).show()<br>        }<br>    }<br></pre><pre>}</pre><p>and by this we get the result we want, doing the heavy work in a IO dispatcher, and showing our results in main Dispatcher.</p><h3>How Coroutines work?</h3><p>If we step back in our article we said that the compiler is responsible to do the coroutine thing for us, but if we want to <a href="https://blog.cleancoder.com/uncle-bob/2015/08/06/LetTheMagicDie.html">make the magic go away</a>, we can convert Kotlin code to byte code, it’s hard to read, so the next step is to decompile it to Java .</p><p>From IntelliJ or Android Studio: <em>tools &gt; Kotlin &gt; Kotlin byte code. then press decompile</em></p><p>We will do that with just a simple suspend function which return welcome message</p><pre>suspend fun welcomeMessage(name: String): String {</pre><pre>    return &quot;Hello $name&quot;</pre><pre>}</pre><p>Equivalent Java code to this will be</p><pre>@Metadata(<br>  ...<br>  ...<br>)<br>public final class SuspendFunctionJavaCodeKt {<br>   @Nullable<br>   public static final Object welcomeMessage(@NotNull String name,  <br>                             @NotNull Continuation $completion) {<br>      return &quot;Hello &quot; + name;<br>   }</pre><pre>}</pre><p>what is important here is there a new argument we didn’t declare in our code which is <strong><em>Continuation</em></strong>.</p><h3>Continuation</h3><pre>@SinceKotlin(&quot;1.3&quot;)<br>public interface Continuation&lt;in T&gt; {<br>  <br>    public val context: CoroutineContext</pre><pre>    public fun resumeWith(result: Result&lt;T&gt;)</pre><pre>}</pre><p>Is an interface which carry the information of the current state, so when it get back to the suspension point it can resume normally with the updated one, and by this we get the behavior intended by writing a sequential code, but it behave asynchronously. There’s <a href="https://youtu.be/jT2gHPQ4Z1Q?t=1697">more</a> than this simple explanation, but I hope you get the idea.</p><p><strong>Further readings</strong></p><ul><li><a href="https://www.youtube.com/watch?v=_hfBv0a09Jc">Introduction to Coroutines.</a></li><li><a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md">The Guide to kotlinx.coroutines by example</a>.</li><li><a href="https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055">Coroutine Context and Scope.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e40cb9a106c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/hello-kotlin-coroutines-4e40cb9a106c">Hello Kotlin Coroutines</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda design patterns]]></title>
            <link>https://medium.com/@mibrahimdev/lambda-design-patterns-d031451fccb1?source=rss-865ef9ea000d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d031451fccb1</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Mohamed Ibrahim]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 15:18:04 GMT</pubDate>
            <atom:updated>2020-03-15T17:01:30.590Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lambda design patterns in Kotlin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NvjXM4fXWh51KDeoaoO6BA.png" /><figcaption>lambda design patterns</figcaption></figure><p>At the beginning of learning programming and Android, writing code for me was just to learn the language and the tools it provides to just finish the job or the task. after some point of writing code, you realize there is some kind of abstraction that could solve the problems with your code.</p><p>Those kind of problems that cause you to rewrite big block of codes with every new requirement, or an update in old features. So <strong>Abstraction</strong> came to save us time and effort, in OOP world this abstraction came in many shapes depend on the problem it try to solve.</p><p>it’s called in software industry as <strong>Design Patterns</strong> and they maybe the OOP in action if I want to describe it. you can’t feel the importance of OOP and the beauty of it without learning them.</p><p>With shifting towards functional programming, it is necessary to spot some patterns that will make the code easier to reason about. and one of the basic principles of functional programming is <strong>Lambda</strong>.</p><p>Lambda in simple words is just the anonymous function, you declare it in Java by an interface with single function. for example if you used a Runnable may look like this</p><pre>Runnable runnable = new Runnable() {<br>    @Override<br>    public void run() {<br>        //do something<br>    }<br>};</pre><p>if you’re writing this in IntelliJ or Android Studio, it show you a hint that you could change that to lambda</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ywOX5g19hOpWfYzm" /></figure><p>clicking the option and the new syntax will be change to this</p><pre>Runnable runnable = () -&gt; {<br>    //do something<br>};</pre><p>What is the difference, well first of all it’s shorter “less code”, second it give you only the signature of the function you use, and in Runnable case it’s just a void function.</p><p>and the way of writing lambda differs in Kotlin, as it doesn’t require you to define an interface with a single function to start to use it. it does that in compile time to be interpolatable with Java. but it doesn’t require you an extra effort. so in Kotlin you could write something like this.</p><pre>val voidFunction = {<br> //do something<br>}</pre><p>and when you try to define the type, it will show you the matching signatures like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mARJYqIkPs46Ccsl" /></figure><p>lambda is just anonymous function without name, you could define it in the go, think of it like it’s a block of code that you defer its execution.</p><p>So any interface with a single function (SAM) you could change it to lambda, all you have to do is define the arguments types and the return type, simply the function signature.</p><p>How does that could shape some of the famous Design patterns in OOP world.</p><h3>Strategy Pattern</h3><pre>class Printer(private val stringFormatterStrategy: Formatter) {</pre><pre>    fun printString(string: String) {<br>        println(stringFormatterStrategy.format(string))<br>    }<br>}</pre><pre>interface Formatter {<br>    fun format(string: String): String<br>}</pre><pre>val lowerCaseFormatter: Formatter = object : Formatter {<br>    override fun format(string: String): String {<br>        return string.toUpperCase()<br>    }<br>}</pre><pre>val upperCaseFormatter: Formatter = object : Formatter {<br>    override fun format(string: String): String {<br>        return string.toUpperCase()<br>    }<br>}</pre><p>The idea of strategy pattern is to code to interface not the implementation, so the argument of the printer in pre Lambda world could be an interface called <em>Formatter</em>, and you have tow separate classes to define, each implement this interface .. in the consumer code, Printer doesn’t care about the implementation, it only cares that the argument should be a <em>Formatter.</em></p><p>but with lambda, you only need to define a lambda signature. and just path whatever implementation you want.</p><pre>class Printer(private val stringFormatterStrategy: (String) -&gt; String) {</pre><pre>    fun printString(string: String) {<br>        println(stringFormatterStrategy.invoke(string))<br>    }<br>}</pre><pre>val upperCaseFormatter: (String) -&gt; String = { it.toUpperCase() }<br></pre><pre>val lowerCaseFormatter: (String) -&gt; String = { it.toLowerCase() }</pre><h3>Command Pattern</h3><p>the idea of command pattern is to decouple the what from when, what you want to run, from when you want to run it, for example you could save a set of code to run it latter, the contract of the command pattern is just an interface with an execute function.</p><pre>interface OrderCommand {<br>    fun execute()<br>}</pre><pre>class OrderAddCommand(val id: Long) : OrderCommand {<br>    override fun execute() = println(&quot;Adding order with id: $id&quot;)<br>}</pre><pre>class OrderPayCommand(val id: Long) : OrderCommand {<br>    override fun execute() = println(&quot;Paying for order with id: $id&quot;)<br>}</pre><pre>class CommandProcessor {</pre><pre>    private val queue = ArrayList&lt;OrderCommand&gt;()</pre><pre>    fun addToQueue(orderCommand: OrderCommand): CommandProcessor =<br>        apply {<br>            queue.add(orderCommand)<br>        }</pre><pre>    fun processCommands(): CommandProcessor =<br>        apply {<br>            queue.forEach { it.execute() }<br>            queue.clear()<br>        }<br>}</pre><p>with lambda</p><pre>class OrderAddCommand(val id: Long) : () -&gt; Unit {<br>    override fun invoke() = println(&quot;Adding order with id: $id&quot;)<br>}</pre><pre>class OrderPayCommand(val id: Long) : () -&gt; Unit {<br>    override fun invoke() = println(&quot;Paying for order with id: $id&quot;)<br>}</pre><pre>class CommandProcessor {</pre><pre>    private val queue = ArrayList&lt;() -&gt; Unit&gt;()</pre><pre>    fun addToQueue(orderCommand: () -&gt; Unit): CommandProcessor =<br>        apply {<br>            queue.add(orderCommand)<br>        }</pre><pre>    fun processCommands(): CommandProcessor =<br>        apply {<br>            queue.forEach { it.invoke() }<br>            queue.clear()<br>        }<br>}</pre><p>And you could use it in both cases like this</p><pre>CommandProcessor()<br>    .addToQueue(OrderAddCommand(1L))<br>    .addToQueue(OrderAddCommand(2L))<br>    .addToQueue(OrderPayCommand(2L))<br>    .addToQueue(OrderPayCommand(1L))<br>    .processCommands()</pre><p>Something different in this example, I declared the class with a lambda type, so it force you to implement the invoke function, and the use case for this, if you have to pass some data to use later. once lambda invoked it has the data it needs.</p><h3>Observer Pattern</h3><p>We use observer pattern when we want to get the updates of an object state. a simple example for this is the UI listeners, like the click listener or the text change listener in the edit text, most of Ui platforms provides you with set of listeners to behave accordingly.</p><p>an old habit it that we used to declare Ui listeners as one interface that include more than one function, in that case you can’t use lambda. So it’s better to untie that interface and make each function of it as SAM.</p><p>if you are an Android developer you should be familiar with the TextWatcher.</p><pre>public interface TextWatcher extends NoCopySpan {</pre><pre>    public void beforeTextChanged(CharSequence s, int start,<br>                                  int count, int after);<br> <br>    public void onTextChanged(CharSequence s, <br>                              int start, int before, int count);</pre><pre>   <br>    public void afterTextChanged(Editable s);<br>}</pre><p>here you can’t just to listen to text changes, you’ll still have to override the other tow, which is annoying .. but the good news that androidx core package provide nicer syntax. you just use what you need.</p><pre>val editText = EditText(this)</pre><pre>editText.addTextChangedListener { <br>   //do something<br> }</pre><p>So observer pattern became just passing lambda.</p><p><em>The idea of passing code that will be executed later is the key of understanding functional programming. this code is usually a lambda. all we need is to define the function signature. and the other is just an implementation detail.</em></p><h3>lambda design patterns</h3><p>if we could write a summer function in old imperative way it may look like this</p><pre>fun totalValues(list: List&lt;Int&gt;): Int {<br>    var sum = 0<br>    for (element in list) {<br>        sum += element<br>    }<br>    return sum<br>}</pre><p>What if we need the sum of just the even values? well a straightforward solution, we could just copy past this function and adding a slight modification.</p><pre>fun totalEvenValues(list: List&lt;Int&gt;): Int {<br>    var sum = 0<br>    for (element in list) {<br>        if (element % 2 == 0) sum += element<br>    }<br>    return sum<br>}</pre><p>now a new requirement came, what if we need the sum of odd values, you got it right, we copy paste and create a third function.</p><pre>fun totalOddValues(list: List&lt;Int&gt;): Int {<br>    var sum = 0<br>    for (element in list) {<br>        if (element % 2 != 0) sum += element<br>    }<br>    return sum<br>}</pre><p>I think you got the idea, but now you have in your belt a powerful tool you could use <strong>lambda</strong>, let’s think what is the piece of code you changed each previous time. and we could just pass it to our total function so we defer the implementation to the user of this function.</p><p>it’s obvious is the condition, we test element and if it pass the the test we add it to the sum, this in lambda could be written like this.</p><pre>fun totalValues(list: List&lt;Int&gt;, selector: (Int) -&gt; Boolean): Int {<br>    var sum = 0<br>    for (element in list) {<br>        if (selector(element)) sum += element<br>    }<br>    return sum<br>}</pre><p>now it’s just one function, when we use it will be just simple as that</p><pre>//sum of even numbers<br>println(totalValues(listOf(1, 2, 3, 4)) { it % 2 == 0 }) </pre><pre>//sum of odd numbers<br>println(totalValues(listOf(1, 2, 3, 4)) { it % 2 != 0 })</pre><p>this lambda we wrote, could be found as <strong>Predicate </strong>interface in Rxjava or even in the functional interfaces in Java8. what we achieved till now that we extracted the changing part of code, made it more flexible.</p><p><em>I hope you get the idea of the importance of using lambda and how it could change the way you write code.</em></p><p><strong><em>Useful resources</em></strong></p><ul><li><a href="https://www.youtube.com/watch?v=e4MT_OguDKg&amp;t=21s">Design Patterns in the Light of Lambda Expressions by Subramaniam</a></li><li><a href="https://github.com/dbacinski/Design-Patterns-In-Kotlin">Design patterns in Kotlin</a></li><li><a href="https://arrow-kt.io/">Arrow: Kotlin functional programming lib</a></li></ul><p>📝 Save this story in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text">Journal</a>.</p><p>👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. <a href="https://usejournal.com/newsletter/noteworthy-in-tech/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_text">Read the Noteworthy in Tech newsletter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d031451fccb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Evolution of Android Architecture patterns]]></title>
            <link>https://medium.com/@mibrahimdev/the-evolution-of-android-architecture-patterns-6ab78b81570a?source=rss-865ef9ea000d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ab78b81570a</guid>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[architecture-pattern]]></category>
            <dc:creator><![CDATA[Mohamed Ibrahim]]></dc:creator>
            <pubDate>Wed, 21 Nov 2018 20:45:01 GMT</pubDate>
            <atom:updated>2018-11-21T20:45:01.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZCB_xbzVh35u199HuudEA.jpeg" /></figure><p>The main problem that Android community started to realize in the last few years is how much coupling in Presentation layer they have in Android apps.</p><p>This led to spaghetti code, that hard to maintain, hard to build up to, and this really hurts the business, so community starts to think of another architecture patterns that make life easier, that minimize the +1000 line Activity classes we have .. Those patterns have one purpose .. “<strong>separate of concerns</strong>”.</p><p>First design pattern we thought that will solve our problems, and put the last nail in the coffin of MVC was the <strong>MVP </strong>pattern<strong>,</strong> which gave us a glimpse of what clean, maintainable code should be, then we’ve became a little bored of writing the getView().doSomeUIThing() .. we thought that a reactive abraoch will solve MVP problems, so we moved a little to <strong>MVVM </strong>pattern where you use the Observer pattern to make View and ViewModel communicate with each other. and that really helped a lot.</p><p>along the way there were tools that either community/Google developed for Android or we discovered and make the use of it .. some of them was a mistake (DataBinding: the writing code in XML part), some of them was a great way to bring functional programming and its way of thinking to the Java world Rxjava as an example.</p><p>after using MVP and MVVM for a while we noticed the State problem, showing an error with loading indicator at the same time, so Hannes Dorfman came with the Mosby and the <strong>MVI</strong> pattern inspired of cycle Js and redux from the Javascript world, which I know nothing about except the names :D, MVI compose some of the great principles to get <a href="https://www.linkedin.com/pulse/clean-code-notes-mohamed-ibrahim/">clean code</a> right.</p><p>One state at a time .. Immutable models, UDF, pure functions, those principle give us a predictable behavior of the UI, which makes debugging a lot more easier.</p><p>if my opinion matters, I’ve worked with the MVP, MVVM and currently playing with MVI and what I think is .. Your situation decides which pattern is the best for you So don’t couple yourself to patterns, or tools, just stick with the big picture, the principles, how to apply those principles with minimum, simple code .. I know this is the hardest thing Developer could do, but as <strong>Leonardo Da Vinci</strong> said once</p><blockquote><em>“simplicity is the ultimate sophistication.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ab78b81570a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Architecture components walk-through]]></title>
            <link>https://medium.com/@mibrahimdev/android-architecture-components-walk-through-b19b439a2f01?source=rss-865ef9ea000d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b19b439a2f01</guid>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[room]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[architecture-components]]></category>
            <dc:creator><![CDATA[Mohamed Ibrahim]]></dc:creator>
            <pubDate>Tue, 29 May 2018 18:13:32 GMT</pubDate>
            <atom:updated>2026-09-03T11:31:28.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*816o7UGcCkIPoryclBx1Qw.jpeg" /></figure><p>It’s been a while since Google has released their sets of Architecture libraries or as they’re calling it “Components” , I didn’t check it once it came out but it took me a couple of days to be amazed by the work they’ve done.</p><p>Usually I love to watch some videos and talks about the subject first, then I try to dive in the code, read some other developers samples, demos and articles finally try to play with it, all this to just decide what’s in it for me.</p><p>So I started to collect those resources to walk through them and see what I can gain from those libraries .. you can find the whole list <a href="https://www.linkedin.com/feed/update/urn:li:activity:6344643393771184128">here</a>.</p><p>This is a quick walk through of the <a href="https://developer.android.com/topic/libraries/architecture/index.html">Android Architecture components</a> and how you can benefit from them.let’s start</p><h3>What are Android Architecture components ?</h3><p>You and me and others are developers, our work flow may be different but we agree that each piece of code it’s like a living being.</p><p>You may start crowd those beings at one place , you may try to organize them a little, but with Android it’s hard to start with a good architecture.</p><p>I think most of us experienced that, many Android community members have <a href="https://github.com/search?o=desc&amp;q=android+architecture+android&amp;s=stars&amp;type=Repositories&amp;utf8=%E2%9C%93">contributed</a> to write cleaner code than what is already exist.</p><p>Those contributions what pushed Google to be part of the solution .. and no one can deny, that they offered a great response to the community .. Kotlin for example, and what we’re talking about now .. Architecture components.</p><blockquote><em>A collection of libraries that help you design robust, testable, and maintainable apps. Start with classes for managing your UI component lifecycle and handling data persistence.</em></blockquote><p>This is from the first page in the official documentation, each component doesn’t rely on the other, so you can use what you find beneficial to you and your team. those libraries as follow:</p><ul><li><strong>LifeCycle Aware</strong>: you don’t need to bloat your activity with overriding lifecycle methods any more.</li><li><strong>ViewModel: </strong>configuration changes handling is not painful any more.</li><li><strong>LiveData</strong>: you don’t have to know Rxjava to write clean code.</li><li><strong>Room</strong>: is it a <a href="https://youtu.be/4eUuD7LsqMs">resurgence of SQL</a>? absolutely.</li><li><strong>Paging library:</strong> didn’t discover it yet, but it’s a library of paging :)</li></ul><p>let’s see what they offer one by one.</p><h3>LifeCycle Aware components</h3><p><strong><em>Use case:</em></strong></p><p>You have a requirement as follow, implement a Google map screen that show User location, and show near by locations (<em>Masjid</em> — Schools — Restaurants) filtered by his interests. and of course all that without draining his battery.</p><p><strong><em>Implementation:</em></strong></p><p>This is some of the implementation related to lifecycle:</p><ul><li>register location listener in onCreate / onStart</li><li>unregister location listener in onDestroy / onStop</li><li>register BroadcastReciever of GPS settings onCreate / onStart</li><li>unregister BroadcastReciever of GPS settings onDestroy / onStop</li><li>cleaning Rxjava Observables any other listeners</li></ul><p><strong><em>Problem:</em></strong></p><p>With more features, comes more lifecycle handling, I didn’t mention configuration changes yet and their effects on the lifeCycle.</p><p>The problem now that the Activity/Fragment is responsible for managing many other instances lifecycle. which bloat the whole class with coupled code.</p><p>just imagine each time you need to add an Rxjava observable or using a resource need to be released in onDestroy/onPause to avoid memory leaks.</p><p><strong><em>Solution:</em></strong></p><p>How could we solve problem like this? well there is the architecure design patterns like (MVP — MVVM — MVI ..) to make Activity/Fragment do only their job, rendering View, the other part is to make any component that deal with Activity/Fragment a lifeCycle aware component.</p><p><strong><em>How to use LifeCycle awre component?</em></strong></p><p>Mainly you have <em>LifeCycleObserver</em><strong><em> </em></strong>interface which make any class capable of monitoring the lifecycle of the<strong> </strong><em>LifeCycleOwner.</em></p><p>The following is from the code lab after removing some implementation</p><p><a href="https://gist.github.com/mibrahimdev/a3199821cc2daf712feba961fa6e0803">https://gist.github.com/mibrahimdev/a3199821cc2daf712feba961fa6e0803</a></p><p>Now you can annotate the methods with the fit lifecycle annotation and it will be executed with no need to call them on the View (Activity/ Fragment)</p><p>The second step is to add this class to LifeCycleOwner observers, and this through <em>getLifeCycle().add().</em> in the Activity</p><p><a href="https://gist.github.com/mibrahimdev/592accc894f4141c8e771fca2681efb6">https://gist.github.com/mibrahimdev/592accc894f4141c8e771fca2681efb6</a></p><p>And by this you can force your library or code to behave the right way with the lifeCycle .. and no need to maintain (onDestroy/onDestroyView — onPause — onResume) code, you simply annotate the method with the right life cycle annotation and let the rest for the library.</p><p>If I remember well, starting from the Support library 26.1.0 theFragment and Activity both are lifeCycle owners. so you can access <em>getLifeCycle()</em> with no additional work.</p><h3><a href="https://www.youtube.com/watch?v=c9-057jC1ZA">ViewModel</a></h3><p>Well I didn’t find better explaination than official docs:</p><blockquote><em>A ViewModel is always created in association with a scope (an fragment or an activity) and will be retained as long as the scope is alive.</em></blockquote><p>E.g. if it is an Activity, until it is finished.</p><p><em>In other words, this means that a ViewModel will not be destroyed if its owner is destroyed for a configuration change (e.g. rotation). The new instance of the owner will just be re-connected to the existing ViewModel.</em></p><p>So you don’t need to handle any data due to this destroy, recreation thing.</p><p><em>The purpose of the ViewModel is to acquire and keep the information that is necessary for an Activity or a Fragment.</em></p><p>keep in mind that ViewModel’s one and only responsibility is to manage the data for the UI.</p><p>It’s interesting to mention here that the ViewModel is just a non UI fragment with <em>setRetainInstance(true)</em>.</p><p><strong><em>Use case</em></strong>:</p><p>You have a Quiz app which has many questions screens, each screen has a simple chronometer that count down the remaining time till the end. the user may rotate the screen to have a better look on the images or the data so he could get the answer.</p><p><strong><em>Problem:</em></strong></p><p>Suddenly the user discover that each time he rotate the phone, the count down timer start over. so he use that to get more time.</p><p><strong><em>Implementation:</em></strong></p><p>There is many solutions to this problem, some of them are bad. some of them are not clean enough, you can google it.</p><p><strong><em>Solution:</em></strong></p><p>You simply hold the data related to UI in a ViewModel instance to live the configuration change.</p><p><strong><em>How to use ViewModel component?</em></strong></p><p>First you create a viewModel with extending the <em>ViewModel</em>, and define the data you want to manage.</p><p><a href="https://gist.github.com/mibrahimdev/452fff795cbf93babad4e20e0f7cbb84">https://gist.github.com/mibrahimdev/452fff795cbf93babad4e20e0f7cbb84</a></p><p>Second, you get your ViewModel instance with the help of the ViweModel factory (provider) method, and finally you access what you need or observe the data.</p><p><a href="https://gist.github.com/mibrahimdev/bd54a6d583f456a2b49bfc0d5e720ec4">https://gist.github.com/mibrahimdev/bd54a6d583f456a2b49bfc0d5e720ec4</a></p><h3>LiveData</h3><p>When I discovered this one, I had one question in mind, why another Observer pattern implementation? we already have Rxjava.</p><p>So the simple answer “from one of I/O talks” that Rxjava has a very steep learning curve, you don’t expect all new comers or newbies developers to learn Rxjava in short time. so LiveData is more like a lightweight Observable.</p><p><strong><em>Use case:</em></strong></p><p>suppose that in your Quiz app, you need to show hints to the user before the time ends let’s say by 5 minutes.</p><p><strong><em>Bad implantation:</em></strong></p><p>you could do that in the Activity, by checking the remaining time, but the logic of picking hints, what time to show, this logic shouldn’t be in the Activity because as we agreed that Activity/Fragment are only view to render the UI.</p><p><strong><em>Solution:</em></strong></p><p>Using the Observer pattern we could observe the timer value and do our logic in the Presenter or in the ViewModel. or better to reverse that by updating timer from the Presenter/ViewModel and Observe in the Activity/Fragment, the following example use the later.</p><p><strong><em>How to use LiveData component?</em></strong></p><p>All you need is to wrap your data with one of the LiveData types ..</p><p><a href="https://gist.github.com/mibrahimdev/b7c1cb2c761629e3ed8358991ca467f4">https://gist.github.com/mibrahimdev/b7c1cb2c761629e3ed8358991ca467f4</a></p><p>Then you use<em> setValue()</em> when you’re on the MainThread or <em>postValue() </em>when you’r on background thread.</p><p>If you tried to swap the usages of the previous methods, you will get an IllegalStateException which is great.</p><pre>java.lang.IllegalStateException: Cannot invoke setValue on a background thread</pre><p>finally you use <em>observe() </em>method to get the data updates.</p><p><a href="https://gist.github.com/mibrahimdev/cb23a511752532600adbeb1eb6486f2a">https://gist.github.com/mibrahimdev/cb23a511752532600adbeb1eb6486f2a</a></p><p>Those are the most essential methods you will use with LiveData.</p><h3>Room</h3><p>Well from the day one knowing about Sqlite, I knew that I don’t like it :), there is much amount of boilerplate code to write Sql in Android, and if you missed one single letter, you will never know till the Runtime.</p><p>I was using <a href="https://github.com/greenrobot/greenDAO">GreenDao</a> as a good way to dealing with Sqlite, but when I discovered Room it’s now my way to go when writing database in Android.</p><blockquote><em>Room is an abstraction layer over Sqlite</em></blockquote><p>and because Room is a fancy way to write database, we will get into it directly.</p><p><strong><em>How to use Room?</em></strong></p><p>1- Annotate your model</p><ul><li>@Entity — annotate a class to have a mapping Sqlite table.</li><li>@PrimaryKey(autoGenerate = true) — annotation to have an index.</li><li>@Ignore — for any constructor or field doesn’t belong to Sqlite.</li></ul><p><a href="https://gist.github.com/mibrahimdev/75a41ce1d9999c272ff9b077eb313dfb">https://gist.github.com/mibrahimdev/75a41ce1d9999c272ff9b077eb313dfb</a></p><p>2- Design your DAO</p><p>You use @Dao to annotate your interface that access the database, and you have @Insert, @Query, @Delete, @Update annotations to represent the Sql database operations.</p><p>With some of them you have some options, for example with update or insert, you have some strategies to choose from to handle conflicts.</p><p>By default those operations <a href="https://developer.android.com/reference/android/arch/persistence/room/RoomDatabase.Builder.html#allowMainThreadQueries()">run on a background thread</a> so it doesn’t block your UI.</p><p><a href="https://gist.github.com/mibrahimdev/5e75b73dfbfd8c7c7f47d0bdcbca8f07">https://gist.github.com/mibrahimdev/5e75b73dfbfd8c7c7f47d0bdcbca8f07</a></p><p>3- Get your RoomDatabase instance</p><p>Create an abstract class that extends <em>RoomDatabase </em>and use the Room builder to build the instance of your database, note that this is an abstract class so the library could generate the required code to wire things up.</p><p>@Database — is used to define the entities (DB tables) and the DB version.</p><p>@TypeConverter — is to use custom converter when getting data from DB. for example to convert the date to human readable format.</p><p><a href="https://gist.github.com/mibrahimdev/062c1c127c966d245074d5fc4935d76f">https://gist.github.com/mibrahimdev/062c1c127c966d245074d5fc4935d76f</a></p><p>4- finally you access your dao from this instance (may be in a repository) and do the operation you need.</p><p><a href="https://gist.github.com/mibrahimdev/c877e74ea9dc8d9de4478e838e8cec0f">https://gist.github.com/mibrahimdev/c877e74ea9dc8d9de4478e838e8cec0f</a></p><p>that’s it for Room</p><h3>Paging library: coming soon.</h3><p>This is was a quick intro to Android Architecture components and I’ll try to add the Paging library section once I finish discovering it.</p><p>To use any of these components or play with them, just head to this documentation <a href="https://developer.android.com/topic/libraries/architecture/adding-components.html">link</a>.</p><p>Any feedback on writing will be appreciated — THANKS</p><p><strong>Resources:</strong><em> </em><a href="https://www.linkedin.com/feed/update/urn:li:activity:6344643393771184128/">https://www.linkedin.com/feed/update/urn:li:activity:6344643393771184128/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b19b439a2f01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I had 10 Android interviews during the last two years, here’s the questions plus some lessons I’ve…]]></title>
            <link>https://medium.com/android-news/i-had-10-android-interviews-during-the-last-two-years-heres-the-questions-plus-some-lessons-i-ve-cdc583dfbc65?source=rss-865ef9ea000d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdc583dfbc65</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Mohamed Ibrahim]]></dc:creator>
            <pubDate>Tue, 14 Nov 2017 20:10:59 GMT</pubDate>
            <atom:updated>2018-01-22T12:17:03.740Z</atom:updated>
            <content:encoded><![CDATA[<h3>I had 10 Android interviews during the last two years, here’s the questions plus some lessons I’ve learned</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_KAc8TqtAvQww7QF06p3Q.jpeg" /></figure><p><em>I wrote this blog post at the Udacity forum, thought sharing it here is a good thing.</em></p><p>2 years passed since I started Android development, I was amazed by the amount of resources out there to learn Android, how the community share knowledge and co-operate to make Android development more fun, and how the Android developers attitude grows from just building things to create testable, maintainable, and easy way to communicate … code.</p><p>Through those 2 years I had bunch of interviews, some go smooth, some not, but each time I look back and see what I missed. Usually the purpose of interviews is to land a job, but it’s also a great way to sense your level of understanding of tools, language and development cycle.</p><p>I’m not a computer science major, so I’ve figured a lot of stuff from reading, watching talks, tutorial and of course Udacity materials, I even had this course with MAL, was named “Android fundamentals” back then, and from that point was my start with Android development.</p><p>So after counting the interviews, they are 10 interviews with many questions, first I’ll list the companies (no names just initials) and the interview style of each, then I’ll list all questions I’ve remembered … let’s start</p><h3>Interviews Styles</h3><p>EP: Regular Android development and Java questions. — Task: Login screen with email and password, user should login automatically the second app use.</p><p>IC: Friendly interview, talking about tools and technologies and code quality. — Task: Non</p><p>SD: testing the flexibility of candidate attitude (e.g your ability to switch between hybrid and native) — Task: make a bucket game that collect one type of falling things.</p><p>AT: Regular Android development and Java questions — Task: Non.</p><p>AR: Regular Android development and Java questions — Task: Non</p><p>SW: Regular Android development and Java questions — Task: Non.</p><p>RA: Questions get harder the more you answer them correctly — Task: Photo app that label captured image with weather info.</p><p>VN: Questions get harder the more you answer them correctly. It was friendly talk too — Task: Non</p><p>IB: Java focused and Questions getting harder — Task: Master detail app that show list of airlines retrieved from server api.</p><p>WM: Java and Android and testing the flexible attitude — Task: Non</p><p>That’s all I hope I didn’t forget something, but why did I list interviews like this? because companies are different, some of them may need an Android developer just to do the job and to do it perfect, they are the big companies usually.</p><p>Others may need an open minded developer, fast learner, could work on other technologies (back-end, System admin … etc), they may be a small companies or startups. And each company has a specific purpose to hire you. So you shouldn’t focus only on the technical stuff, do your search about the company, try their apps before the interview. Prepare your question to ask them, because it’s not a one way interview, and it never has been one.</p><p>I’ll list the questions now, and it’s better to not find one answer for each question and memories it, this is very bad … try to read stackoverflow threads about the subject, read the comments too, I found it the best place that explain technical subjects to humans, because everyone there is trying to explain it the best.</p><p>Try to do sample apps, for example if you can’t understand the Fragment lifecycle, you could do a simple demo with logging messages to know what’s going on. Google samples are a good way to discover things too.</p><h3>Interviews Questions with no specific order:</h3><p>1- what are the latest Android versions? The most important Marshmallow new features?</p><p>2- what is the purpose of the Activity?</p><p>3- what is the purpose of the Fragments?</p><p>4- explain the lifeCycle of the Activity?</p><p>5- explain the lifeCycle of the Fragment?</p><p>6- you’re using a traveling app then you clicked settings button, Settings Activity opened, then you click Android back, what’s the lifeCycle of the Settings Activity and the Home Activity when you did that?</p><p>7- what do you know about Material design?</p><p>8- what’s the difference between Abstract class and Interface in Java?</p><p>9- what’s an Interface in Java?</p><p>10- what’s an Abstract class in Java?</p><p>11- why you couldn’t create an instance from an abstract class?</p><p>12- what’s the difference between Dialog and AlertDialog in Android?</p><p>13- what’s the difference between LinearLayout and RelativeLayout?</p><p>14- which has better performance, LinearLayout or RelativeLayout?</p><p>15- given a simple contact item, with image and name and number, how could you implement it in XML?</p><p>16- what’s the Service, which thread it operates on?</p><p>17- what’s the difference between Service and IntentService?</p><p>18- what’s ANR message?</p><p>19- explain the BroadcastReciever job and implementation?</p><p>20- can you use a Fragment with no UI? What cases could make you use this pattern?</p><p>21- explain the Java access modifiers?</p><p>22- what’s the difference between Default and Protected access modifiers in Java?</p><p>23- what do you know about AsyncTask?</p><p>24- what’s the difference between Parcelable and Serializable? Which one is better? why?</p><p>25- how to access a variable in Activity from fragment?</p><p>26- you have one Activity with two fragments, one has a button and the second has a TextView, clicking the button change the TextView, how do you implement it?</p><p>27- how to make a variable thread safe?</p><p>28- what strategies we can use to achieve thread safety?</p><p>29- what is the purpose of “static” keyword in Java?</p><p>30- how could you initialize a static variable in Java?</p><p>31- what design patterns you know?</p><p>32- explain the builder pattern?</p><p>33- when do you use an observer pattern?</p><p>33- what’s the Singleton, when do you use it in Android?</p><p>34- what’s the difference between the LinkedList, ArrayList and Arrays?</p><p>35- what projects currently you work on? What is your workflow to implement a specific feature?</p><p>36- how do you handle Firebase push notifications?</p><p>37- how do you implement Firebase realtime Database?</p><p>38- you have a big project, and you have a login screen requirement, what processes you will follow to ship it?</p><p>39- what’s an Eventbus?</p><p>40- what the thread that onRecieve() method of a BroadcastReceiver operates on?</p><p>41- how to implement a custom BroadcastReceiver?</p><p>42- what’s the difference between MVC and MVP?</p><p>43- could you explain MVVM?</p><p>44- what’s the M in MVP? Answering … could it be a something else?</p><p>45- what’s the purpose of Content Provider?</p><p>46- what Sqlite library do you use?</p><p>47- what libraries do you use for Networking, Image loading, Database?</p><p>48- what do you use to handle a very fast Sensor that emit many readings at a time in Rx way?</p><p>49- what’s the difference between map and flatMap() in Rxjava?</p><p>50- how to create parallel Network calls with Rxjava?</p><p>51- if you have one request from the network and you want to call the cache if Network throw an error … how to achieve that via Rxjava?</p><p>The funny thing that I’ve read Dan lew blog post about this case, implemented it twice before, but couldn’t answering this question during the interview … bad things happen.</p><p>52- what’s the difference between concatMap() and flatMap() in Rxjava?</p><p>53- what do you know about Intents? What is the purpose of categories in Intents?</p><p>54- what’s the purpose of FrameLayout?</p><p>55- how to compare between Two objects?</p><p>56- Java is pass by Value or pass by Reference?</p><p>57- when you use observeOn() and subscribeOn()?</p><p>Well that’s all I can remember for now, usually the OOP, Android components and Design patterns stuff are common among most of the interviews I had.</p><p>Luckily the Android dev challenge course has the answers of many of the questions above, just don’t rush … take your time to understand the basics. Don’t jump into things like Rxjava or Dagger without a good playground of the basics and the platform APIs.</p><p><strong>PS: hope this could help someone, and forgive my horrible English, I’m not a native speaker.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdc583dfbc65" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/i-had-10-android-interviews-during-the-last-two-years-heres-the-questions-plus-some-lessons-i-ve-cdc583dfbc65">I had 10 Android interviews during the last two years, here’s the questions plus some lessons I’ve…</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>