<?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 ISOP on Medium]]></title>
        <description><![CDATA[Stories by ISOP on Medium]]></description>
        <link>https://medium.com/@isopproject?source=rss-86d920e9d27------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*O5-EilxripTgYuWj.jpg</url>
            <title>Stories by ISOP on Medium</title>
            <link>https://medium.com/@isopproject?source=rss-86d920e9d27------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:47:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@isopproject/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[Good practise to use Equals and Hashcode Method in Hibernate]]></title>
            <link>https://medium.com/isop-nepal/good-practise-to-use-equals-and-hashcode-method-in-hibernate-c6b31616ccc0?source=rss-86d920e9d27------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6b31616ccc0</guid>
            <category><![CDATA[entity]]></category>
            <category><![CDATA[hibernate-jpa]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[ISOP]]></dc:creator>
            <pubDate>Thu, 02 Dec 2021 17:00:28 GMT</pubDate>
            <atom:updated>2021-12-02T17:00:28.254Z</atom:updated>
            <content:encoded><![CDATA[<p>Hibernate is a popular, open-source Java persistent framework, which provides Object Relational Mapping, also known as the ORM framework. It uses the equals and hashcode method to provide an object’s equality on the Java side. You should <strong>override equals() and hashcode()</strong> if :</p><p>1) You are storing instances of the persistent class in a Set for representing many-valued associations.</p><p>2) You are using reattachment of detached persistent instances.</p><p>Another worth noting point is that Hibernate only guarantees equivalence of database row (persistent identity) and Java object inside a particular Session. This means if you store instances retrieved in different Sessions in a Set, you will be having duplicates. Now the most important aspect of overriding equals and hashcode() for hibernate entity classes, you should never decide equality just based upon identifier.</p><p>Though it’s convenient to compare identifiers to see if they belong to the same database row, Unfortunately, we can’t use this approach with generated identifiers. Since Hibernate only assigns identifier values to object that is persistent, a newly created instance will not have any identifier value.</p><p>Similarly, if an instance is not persisted, and currently in a Set, saving it to the database will assign an identifier value, which will further change the value of the hashcode() method, finally resulting in breaking the contract of the Set.</p><p>That’s why it’s best to implement equals and hashcode in Hibernate using business key equality e.g. an Employee is the same if its name, surname, father’s name, department, date of birth is same. Properties which are not prone to change e.g. date of birth are better candidate of business equality than those which is easier to change e.g. address and contact number.</p><p>In short, remember these best practices while overriding equals() and hashcode() for Hibernate entity class :</p><p>1) Don’t let your equals() method only uses identifier values for equivalence check.</p><p>2) Implement equals() and hashCode() using real word key that would identify instance in real world.</p><p>3) Use Immutable and unique properties of objects for equality.</p><p>4) Don’t use <a href="http://javarevisited.blogspot.sg/2012/09/how-to-determine-type-of-object-runtime-identification.html">getClass()</a> to compare object equality because Hibernate uses proxy and this check will always fail. Instead, use instanceof operator, it respect proxy because they have IS-A relationship with the actual object.</p><p>5) Use getter and setter methods to access properties instead of directly accessing the, because hibernate lazily initialize object, when there getProperty() method is called. Using name may return null but getName() may return value from database.</p><p>That’s all about <strong>overriding equals() and hashcode() methods in Java</strong>, I am reiterating this but its imperative for a Java programmer to be able to write equals, hashcode(), compareTo() method by hand. It is not just useful for learning purpose but to clear any coding exercise during Java interviews. Writing code for equals and hashcode is very popular programming interview questions now days.</p><p>For Hibernate persistent class its rather tricky to override equals() and hashCode() because otherwise bad practices turns into best practices because of extensive of proxy. You should not use Eclipse IDE code generator for equals() and hashCode() for hibernate entity class, as they use getClass() to check type equality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6b31616ccc0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/isop-nepal/good-practise-to-use-equals-and-hashcode-method-in-hibernate-c6b31616ccc0">Good practise to use Equals and Hashcode Method in Hibernate</a> was originally published in <a href="https://medium.com/isop-nepal">ISOP Nepal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Android podcast app with Jetpack Compose and ExoPlayer.]]></title>
            <link>https://medium.com/isop-nepal/building-android-podcast-app-with-jetpack-compose-and-exoplayer-7f95dd3e5bab?source=rss-86d920e9d27------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f95dd3e5bab</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-hilt]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[exoplayer]]></category>
            <dc:creator><![CDATA[ISOP]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 17:05:52 GMT</pubDate>
            <atom:updated>2021-06-06T17:55:21.069Z</atom:updated>
            <content:encoded><![CDATA[<p>Used Listen Note API (<a href="https://www.listennotes.com/">https://www.listennotes.com/</a>).</p><h3><strong>Features</strong></h3><ul><li>Jetpack Compose UI. Custom animations, transitions, light/dark theme, and layouts.</li><li>Jetpack Compose Navigation.</li><li>Dependency injection with Hilt.</li><li>MVVM Architecture.</li><li>Retrieves podcasts metadata from the network.</li><li>Allows background playback using a foreground service.</li><li>Media style notifications.</li><li>Uses a `MediaBrowserService` to control and expose the current media session.</li><li>Controls the current playback state with actions such as play/pause, skip to next/previous, shuffle, repeat and stop.</li><li>Supports offline playback using `CacheDataSource` from `ExoPlayer`.</li><li>Process images to find their color palette using Palette API.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba4ea7417664e376339addd103d7c5eb/href">https://medium.com/media/ba4ea7417664e376339addd103d7c5eb/href</a></iframe><p>Full code: <a href="https://github.com/yadavraju/ISOP-PODCAST-APP">https://github.com/yadavraju/ISOP-PODCAST-APP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f95dd3e5bab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/isop-nepal/building-android-podcast-app-with-jetpack-compose-and-exoplayer-7f95dd3e5bab">Building Android podcast app with Jetpack Compose and ExoPlayer.</a> was originally published in <a href="https://medium.com/isop-nepal">ISOP Nepal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resources to prepare for technical interview]]></title>
            <link>https://medium.com/isop-nepal/resources-to-prepare-for-technical-interview-3f918cbf9efa?source=rss-86d920e9d27------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f918cbf9efa</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[awa]]></category>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[careers]]></category>
            <dc:creator><![CDATA[ISOP]]></dc:creator>
            <pubDate>Fri, 26 Mar 2021 18:37:07 GMT</pubDate>
            <atom:updated>2021-03-26T18:37:07.353Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Technical interviews are difficult. So I decided to gather resources that will help you crush your next interview.</p><h3>1. Coding Interview University</h3><p>A complete computer science study plan to become a software engineer.</p><p>Link: <a href="https://github.com/jwasham/coding-interview-university">github.com/jwasham/coding-interview-univers..</a></p><h3>2. JavaScript Algorithms</h3><p>Algorithms and data structures implemented in JavaScript with explanations and links to further readings</p><p>Link: <a href="https://github.com/trekhleb/javascript-algorithms">github.com/trekhleb/javascript-algorithms</a></p><h3>3. Tech Interview Handbook</h3><p>Materials to help you rock your next coding interview</p><p>Link: <a href="https://yangshun.github.io/tech-interview-handbook/">yangshun.github.io/tech-interview-handbook</a></p><h3>4. OG AWS</h3><p>Amazon Web Services — a practical guide</p><p>Link: <a href="https://github.com/open-guides/og-aws">github.com/open-guides/og-aws</a></p><h3>5. JavaScript Questions</h3><p>A long list of (advanced) JavaScript questions, and their explanations.</p><p>Link: <a href="https://github.com/lydiahallie/javascript-questions">github.com/lydiahallie/javascript-questions</a></p><h3>6. The System Design Primer</h3><p>Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards.</p><p>Link: <a href="https://github.com/donnemartin/system-design-primer">github.com/donnemartin/system-design-primer</a></p><h3>7. Interview</h3><p>Everything you need to prepare for your technical interview.</p><p>Link: <a href="https://github.com/Olshansk/interview">github.com/Olshansk/interview</a></p><h3>8. Awesome Interviews</h3><p>A curated awesome list of lists of interview questions.</p><p>Link: <a href="https://github.com/MaximAbramchuck/awesome-interview-questions">github.com/MaximAbramchuck/awesome-intervie..</a></p><h3>9. Interviews</h3><p>Everything you need to know to get the job.</p><p>Link: <a href="https://github.com/kdn251/interviews">github.com/kdn251/interviews</a></p><h3>10. React Interview Questions &amp; Answers</h3><p>List of top 500 ReactJS Interview Questions &amp; Answers.</p><p>Link: <a href="https://github.com/sudheerj/reactjs-interview-questions">github.com/sudheerj/reactjs-interview-quest..</a></p><h3>11. Coding Interviews</h3><p>This repository contains coding interviews that I have encountered in company interviews.</p><p>Link: <a href="https://github.com/jayshah19949596/CodingInterviews">github.com/jayshah19949596/CodingInterviews</a></p><h3>12. Reverse interview</h3><p>Questions to ask the company during your interview.</p><p>Link: <a href="https://github.com/viraptor/reverse-interview">github.com/viraptor/reverse-interview</a></p><h3>13. Front end Interview Questions</h3><p>Help the front End community to rock interview.</p><p>Link: <a href="https://thatjsdude.com/interview/">thatjsdude.com/interview</a></p><h3>14. 70 JavaScript Interview Questions</h3><p>Link: <a href="https://dev.to/macmacky/70-javascript-interview-questions-5gfi">dev.to/macmacky/70-javascript-interview-que..</a></p><h3>15. Back-End Developer Interview Questions</h3><p>A list of back-end-related questions you can be inspired from to interview potential candidates, test yourself, or completely ignore.</p><p>Link: <a href="https://github.com/arialdomartini/Back-End-Developer-Interview-Questions">github.com/arialdomartini/Back-End-Develope..</a></p><p>If you liked this article, be sure to ❤️ it.</p><h3>Happy coding! ❤️</h3><p><a href="https://hashnode.com/n/career">#career</a><a href="https://hashnode.com/n/codenewbies">#codenewbies</a><a href="https://hashnode.com/n/github">#github</a><a href="https://hashnode.com/n/aws">#aws</a></p><p>Share this</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f918cbf9efa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/isop-nepal/resources-to-prepare-for-technical-interview-3f918cbf9efa">Resources to prepare for technical interview</a> was originally published in <a href="https://medium.com/isop-nepal">ISOP Nepal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flow in Kotlin and how to use it in Android Project?]]></title>
            <link>https://medium.com/isop-nepal/flow-in-kotlin-and-how-to-use-it-in-android-project-39cddb356507?source=rss-86d920e9d27------2</link>
            <guid isPermaLink="false">https://medium.com/p/39cddb356507</guid>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotli]]></category>
            <dc:creator><![CDATA[ISOP]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 16:10:46 GMT</pubDate>
            <atom:updated>2020-06-20T16:10:46.865Z</atom:updated>
            <content:encoded><![CDATA[<p>With Kotlin Coroutine 1.2.0 alpha release <strong>Jetbrains</strong> came up with Flow API as part of it. With Flow in Kotlin now you can handle a stream of data that emits values sequentially.</p><p><strong><em>In Kotlin, Coroutine is just the scheduler part of RxJava but now with Flow APIs, it can be alternative to RxJava in Android</em></strong></p><h3>What is Flow APIs in Kotlin Coroutines?</h3><p>Flow API in Kotlin is another better way to handle the stream of data asynchronously that executes sequentially.</p><p>So, in RxJava, Observables type is an example of a structure that represents a stream of items. Its body does not get executed until it is subscribed to by a subscriber. and <strong>once it is subscribed</strong>, subscriber starts getting the data items emitted. Similarly, Flow works on the same condition where the code inside a <em>flow</em> builder does not run until the <strong><em>flow</em> is collected</strong>.</p><p>Let us create an android project and then let’s start integrating the Kotlin Flow APIs.</p><h3>Step 01.</h3><p>Add the following in the app’s <strong>build.gradle,</strong></p><pre>implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3&quot;<br>implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3&quot;</pre><p>and in the project’s <strong>build.Gradle </strong>adds,</p><pre>classpath &quot;org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.61&quot;</pre><h3>Step 02.</h3><p>In FlowConceptActivity’s layout file let’s create a UI that will have a button.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout <br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.FlowConceptActivity&quot;&gt;</pre><pre>    &lt;Button<br>        android:id=&quot;@+id/button&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        android:text=&quot;Learn Kotlin Flow&quot;<br>        app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>        app:layout_constraintRight_toRightOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;</pre><pre>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><h3>Step 03.</h3><p>Now, let’s begin the implementation of Flow APIs in FlowConceptActivity. In <strong>onCreate</strong>() function of Activity lets add two function like,</p><pre>override fun <strong>onCreate</strong>(savedInstanceState: Bundle?) {<br>    <strong>super</strong>.onCreate(savedInstanceState)<br>    setContentView(R.layout.activity_main)<br>    startFlow()<br>    buttonClicks()<br>}</pre><p>Here, <strong><em>startFlow</em></strong>() is the function where we will define the flow and <strong><em>buttonClicks</em></strong>() is the function where we will click the button to display the data which is emitted from the flow.</p><p>We will declare a lateinit variable of Flow of Int type,</p><pre>lateinit var flow: Flow&lt;Int&gt;</pre><h3>Step 04.</h3><p>Now, in <strong><em>startFlow</em></strong>() it will emit value after 500milliseconds delay.</p><pre><strong>private fun </strong>startFlow() {<br>    <strong>flow </strong>= <em>flow </em><strong>{<br>        </strong>Log.d(<em>TAG</em>, <strong>&quot;flow Start&quot;</strong>)<br>        (0..10).<em>forEach </em><strong>{<br>            </strong><em>// Emit items with 500 milliseconds delay<br>            </em>delay(500)<br>            Log.d(<em>TAG</em>, <strong>&quot;Emitting value $it&quot;</strong>)<br>            emit(<strong>it</strong>)<br><br>        <strong>}<br>    }</strong>.<em>flowOn</em>(Dispatchers.<strong>Default</strong>)<br>}</pre><p>Here,</p><ul><li>We will emit value from 0 to 10 at <strong>500ms</strong> delay.</li><li>To emit the value we will use <strong>emit() </strong>which collects the value emitted<em>. </em>It is part of FlowCollector which can be used as a receiver.</li><li>and, at last, we use <strong>flowOn</strong> operator which means that shall be used to change the context of the flow emission. Here, we can use different Dispatchers like IO, Default, etc.</li><li><strong>flowOn() is similar to subscribeOn() in RxJava</strong></li></ul><h3>Step 05.</h3><p>Now, we need to write <strong><em>buttonClicks</em>()</strong> function where we need to print the values which we will emit from the flow.</p><pre><strong>private</strong> fun <strong><em>buttonClicks</em></strong>() {<br>    button.setOnClickListener {<br>        CoroutineScope(Dispatchers.Main).launch {<br>            flow.collect {<br>                Log.d(TAG, it.toString())<br>            }<br>        }<br>    }<br>}</pre><p>When we click the button we will print the values one by one.</p><p><strong>flow.collect </strong>now will start extracting/collecting the value from the flow on the Main thread as <strong>Dispatchers.Main</strong> is used in launch coroutine builder in CoroutineScope</p><p>And the output which will be printed in Logcat is,</p><pre>D/FlowConceptActivity: flow Start<br>D/FlowConceptActivity: Emitting value 0<br>D/FlowConceptActivity: 0<br>D/FlowConceptActivity: Emitting value 1<br>D/FlowConceptActivity: 1<br>D/FlowConceptActivity: Emitting value 2<br>D/FlowConceptActivity: 2<br>D/FlowConceptActivity: Emitting value 3<br>D/FlowConceptActivity: 3<br>D/FlowConceptActivity: Emitting value 4<br>D/FlowConceptActivity: 4<br>D/FlowConceptActivity: Emitting value 5<br>D/FlowConceptActivity: 5<br>D/FlowConceptActivity: Emitting value 6<br>D/FlowConceptActivity: 6<br>D/FlowConceptActivity: Emitting value 7<br>D/FlowConceptActivity: 7<br>D/FlowConceptActivity: Emitting value 8<br>D/FlowConceptActivity: 8<br>D/FlowConceptActivity: Emitting value 9<br>D/FlowConceptActivity: 9<br>D/FlowConceptActivity: Emitting value 10<br>D/FlowConceptActivity: 10</pre><p>As you can see Flow starts only when the button is clicked as it prints <strong><em>Start Flow </em></strong>and then starts emitting. This is what I meant by <strong><em>Flows are cold.</em></strong></p><p>Let’s say we update the <strong><em>startFlow</em></strong>() function like,</p><pre><strong>private</strong> fun <strong><em>startFlow</em></strong>() {<br>    flow = flow {<br>        Log.d(<em>TAG</em>, <strong>&quot;flow Start&quot;</strong>)<br>        (0..10).forEach {<br>            <em>// Emit items with 500 milliseconds delay</em><br>            delay(500)<br>            Log.d(<em>TAG</em>, <strong>&quot;Emitting value $it&quot;</strong>)<br>            emit(it)<br>        }<br>    }.map {<br>        it * it<br>    }.flowOn(Dispatchers.Default)<br>}</pre><p>Here you can see we added map operator which will take each and every item will square itself and print the value.</p><p>Anything, written above <strong>flowOn</strong> will run in the background thread.</p><h3>Builders in Flow</h3><p>Flow builders are nothing but the way to build Flows. There are 4 types of flow builders,</p><ul><li><strong>flowOf() — </strong>It is used to create flow from a given set of values. For Eg.</li></ul><pre>flowOf(4, 2, 5, 1, 7).onEach { delay(400) }.flowOn(Dispatcher.Default)</pre><p>Here<strong>, flowOf() </strong>takes fixed values and prints each of them after a delay of 400ms. When we attach a collector to the flow, we get the output</p><pre>D/FlowConceptActivity: 4<br>D/FlowConceptActivity: 2<br>D/FlowConceptActivity: 5<br>D/FlowConceptActivity: 1<br>D/FlowConceptActivity: 7</pre><ul><li><strong>asFlow() — </strong>It is an extension function that helps to convert type into flows. For Eg,</li></ul><pre>(1..5).asFlow().onEach{ delay(300)}.flowOn(Dispatchers.Default)</pre><p>Here, we converted a range of values from 1 to 5 as flow and emitted each of them at a delay of 300ms. When we attach a collector to the flow, we get the output,</p><pre>D/FlowConceptActivity: 1<br>D/FlowConceptActivity: 2<br>D/FlowConceptActivity: 3<br>D/FlowConceptActivity: 4<br>D/FlowConceptActivity: 5</pre><p>The output is the number being printed from 1 to 5, whichever were present in the range.</p><ul><li><strong>flow{} — </strong>This example has been explained in the Android Example above. This is a builder function to construct arbitrary flows.</li><li><strong>channelFlow{}</strong> — This builder creates cold-flow with the elements using <strong>send </strong>provided by the builder itself. For Example,</li></ul><pre>channelFlow {<br>    (0..10).forEach {<br>        send(it)<br>    }<br>}.flowOn(Dispatchers.Default)</pre><p>This will print,</p><pre>D/FlowConceptActivity: 0<br>D/FlowConceptActivity: 1<br>D/FlowConceptActivity: 2<br>D/FlowConceptActivity: 3<br>D/FlowConceptActivity: 4<br>D/FlowConceptActivity: 5<br>D/FlowConceptActivity: 6<br>D/FlowConceptActivity: 7<br>D/FlowConceptActivity: 8<br>D/FlowConceptActivity: 9<br>D/FlowConceptActivity: 10</pre><blockquote><strong>flowOn() is similar to subscribeOn() in RxJava</strong></blockquote><blockquote><strong>Now, finally, let’s discuss how to use an operator of Flow in your project</strong></blockquote><h3>Zip Operator</h3><p>If you remember from above Android Example, we have two functions <strong><em>startFlow</em></strong>() and <strong><em>buttonClicks</em></strong>(). We will modify both functions in MainActivity.</p><p>First, we will declare two lateinit variables of Flow of String type,</p><pre>lateinit var flowOne: Flow&lt;String&gt;<br>lateinit var flowTwo: Flow&lt;String&gt;</pre><p>Now, the two functions <strong><em>startFlow</em></strong>() and <strong><em>buttonClicks</em></strong>() will be called in onCreate() of MainActivity.</p><pre>override fun <strong>onCreate</strong>(savedInstanceState: Bundle?) {<br>    ...<br>    <strong><em>startFlow</em></strong>()<br>    <strong><em>buttonClicks</em></strong>()</pre><pre>}</pre><p>and in the <strong><em>startFlow</em></strong>() we will initialize two flows to the two variables,</p><pre><strong>private</strong> fun <strong>setupFlow</strong>() {<br>    flowOne = flowOf(&quot;Raju&quot;, &quot;Manish&quot;, &quot;Milan&quot;).flowOn(Dispatchers.Default)<br>    flowTwo = flowOf(&quot;Yadav&quot;, &quot;Chaudhary&quot;, &quot;Rai&quot;).flowOn(Dispatchers.Default)</pre><pre>}</pre><p>and in <strong><em>buttonClicks</em></strong>() we will zip both the flows using zip operator,</p><pre><strong>private</strong> fun <strong><em>buttonClicks</em></strong>() {<br>    button.setOnClickListener {<br>        CoroutineScope(Dispatchers.Main).launch {<br>            flowOne.zip(flowTwo)<br>            { firstName, lastName-&gt;<br>                &quot;$firstName $lastName&quot;<br>            }.collect {<br>                Log.d(TAG, it)<br>            }<br>        }<br>    }<br>}</pre><p>Here,</p><ul><li>when the button is clicked the scope is launched.</li><li><strong>flowOne</strong> is zipped with <strong>flowTwo</strong> to give a pair of values that we have created a string and,</li><li>then we collect it and print it in Logcat. The resulting output will be,</li></ul><pre>D/FlowConceptActivity: Raju Yadav<br>D/FlowConceptActivity: Manish Chaudhary<br>D/FlowConceptActivity: Milan Rai</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39cddb356507" width="1" height="1" alt=""><hr><p><a href="https://medium.com/isop-nepal/flow-in-kotlin-and-how-to-use-it-in-android-project-39cddb356507">Flow in Kotlin and how to use it in Android Project?</a> was originally published in <a href="https://medium.com/isop-nepal">ISOP Nepal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Dart for Java Developers-Part1]]></title>
            <link>https://medium.com/isop-nepal/introduction-to-dart-for-java-developers-part1-c2d7303d8afc?source=rss-86d920e9d27------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2d7303d8afc</guid>
            <category><![CDATA[dart-for-java-developers]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[ISOP]]></dc:creator>
            <pubDate>Thu, 15 Aug 2019 04:26:17 GMT</pubDate>
            <atom:updated>2019-08-15T04:32:40.443Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This tutorial gives a core overview of the programming language Dart</em></p><p>Dart is an open-source general-purpose programming language. It is originally developed by Google and later approved as a standard by ECMA. Dart is a new programming language meant for the server as well as the browser. Introduced by Google, the <strong>Dart SDK</strong> ships with its compiler — the <strong>Dart VM</strong>. The SDK also includes a utility <strong>-dart2js</strong>, a transpiler that generates JavaScript equivalent of a Dart Script. This tutorial provides a basic level understanding of the Dart programming language.</p><h3>Audience</h3><p>This tutorial will be quite helpful for all those developers who want to develop single-page web applications, a mobile app (for Flutter) a using Dart. It is meant for programmers with a stronghold on object-oriented concepts.</p><h3>Prerequisites</h3><p>The tutorial assumes that readers have adequate exposure to object-oriented programming concepts. If you have worked on Java, then it will help you further to grasp the concepts of Dart quickly. Don’t worry if you don’t have any programming knowledge experience still you can grasp the concepts of Dart quickly.</p><h3>What you’ll learn</h3><ul><li>Installation</li><li>How to create constructors</li><li>Different ways to specify parameters</li><li>When and how to create getters and setters</li><li>How Dart handles privacy</li><li>How to create factories</li><li>How functional programming works in Dart</li><li>Other core Dart concepts</li></ul><h3>Executing Script Online with DartPad</h3><p>You may test your scripts online by using the online editor at <a href="https://dartpad.dartlang.org/">https://dartpad.dartlang.org/</a>. The Dart Editor executes the script and displays both HTML as well as console output. The online editor is shipped with a set of preset code samples.</p><p>A screenshot of the <strong>Dartpad</strong> editor is given below −</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/0*E1xHVmFzWCFCr9Qn.jpg" /></figure><p>Dartpad also enables to code in a more restrictive fashion. This can be achieved by checking the Strong mode option on the bottom right of the editor. You may try the following example using Dartpad</p><pre>void main() { <br>   print(&#39;hello world&#39;); <br>}</pre><p>The code will display the following output</p><pre>hello world</pre><h3>Setting Up the Local Environment</h3><p>In this section, let us see how to set up the local environment.</p><h3>Using the Text Editor</h3><p>Examples of a few editors include Windows Notepad, Notepad++, Emacs, vim or vi, etc. Editors may vary from one Operating System to another. The source files are typically named with the extension “.dart”.</p><h3>Installing the Dart SDK</h3><p>The current stable version of Dart is 2<strong>.4.0</strong>. The <strong>dart SDK</strong> can be downloaded from −</p><ul><li><a href="https://www.dartlang.org/install/archive/">https://www.dartlang.org/install/archive</a></li><li><a href="http://www.gekorm.com/dart-windows/">http://www.gekorm.com/dart-windows/</a></li></ul><p>A screenshot of the Dart SDK installation is given below −</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/0*c4WAUfM614cvGaiO.jpg" /></figure><p>On completion of the SDK installation, set the PATH environment variable to</p><pre>&lt;dart-sdk-path&gt;\bin</pre><h3>Verifying the Installation</h3><p>To verify if Dart has been successfully installed, open the command prompt and enter the following command −</p><pre>Dart</pre><p>If the installation is successful, it will show the dart runtime.</p><h3>IDE Support</h3><p>Examples include <strong>Eclipse, IntelliJ</strong>, and <strong>WebStorm</strong>from Jet brains. Given below are the steps for configuring the Dart environment using <strong>WebStrom IDE</strong>.</p><h3>Installing WebStorm</h3><p>The installation file for WebStorm can be downloaded from <a href="https://www.jetbrains.com/webstorm/download/#section=windows-version">https://www.jetbrains.com/webstorm/download/#section=windows-version.</a></p><p>The WebStorm installation file is available for Mac OS, Windows, and Linux. After downloading the installation files, follow the steps given below −</p><ul><li>Install the Dart SDK: Refer to the steps listed above</li><li>Create a new Dart project and configure Dart support</li><li>To create a new Dart project,</li><li>Click <strong>Create New Project</strong> from the Welcome Screen</li><li>In the next dialog box, click <strong>Dart</strong></li><li>If there is no value specified for the <strong>Dart SDK</strong> path, then provide the SDK path. For example, the SDK path may be <strong>&lt;dart installation directory&gt;/dart/dartsdk</strong>.</li></ul><h3>Add a Dart File to the Project</h3><p>To add a Dart file to the Project −</p><ul><li>Right-click on the Project</li><li>New → Dart File</li><li>Enter the name of the Dart file</li></ul><p>A screenshot of the WebStorm Editor is given below −</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*skRQhSyEfnhZxDmu.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2d7303d8afc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/isop-nepal/introduction-to-dart-for-java-developers-part1-c2d7303d8afc">Introduction to Dart for Java Developers-Part1</a> was originally published in <a href="https://medium.com/isop-nepal">ISOP Nepal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detect vulnerable dependencies in IntelliJ IDEA]]></title>
            <link>https://medium.com/isop-nepal/detect-vulnerable-dependencies-in-intellij-idea-44bb287affd0?source=rss-86d920e9d27------2</link>
            <guid isPermaLink="false">https://medium.com/p/44bb287affd0</guid>
            <category><![CDATA[snyk]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[snyk-vulnerability]]></category>
            <category><![CDATA[dependencies]]></category>
            <category><![CDATA[intellij-idea]]></category>
            <dc:creator><![CDATA[ISOP]]></dc:creator>
            <pubDate>Sun, 23 Jun 2019 05:22:38 GMT</pubDate>
            <atom:updated>2019-06-23T05:22:38.314Z</atom:updated>
            <content:encoded><![CDATA[<p>How to detect and fix security vulnerabilities in your dependencies using Snyk?</p><p>Making sure your application is as secure as possible is very important. Having security vulnerabilities can lead to serious consequences if they are exploited. You should always make sure your own code is as safe as possible.</p><p>However, the core code of your application, which you write yourself, is only the tip of an iceberg. These days, the vast majority of the deployed code is not what you write yourself, but rather various third-party libraries and frameworks. Even the simplest web applications usually have hundreds of thousands of lines of code, which are brought with third-party dependencies.</p><p>It is very hard to make big and complex frameworks secure. Not only are they very complicated, but they also depend on numerous dependencies of their own. It is not a question IF your libraries contain security vulnerabilities, but rather WHEN they are discovered. Once discovered, they are usually fixed quickly, and the next version is released.</p><p>The problematic part is that applications are not that fast with adopting new versions with security fixes. It can take months or even years to upgrade. First of all, you have to know there is a new version. Then you have to know whether to upgrade or not. Were there important security fixes or just some minor bugfixes? Is the fix important enough to justify upgrading cost, especially if there were changes breaking the backward compatibility?</p><h4>Detecting vulnerabilities automatically</h4><p>In the past, detecting vulnerable dependencies was difficult. There were public databases of security vulnerabilities, but you had to check them manually. Needless to say that only a minority of developers bothered to check. It was just too much trouble.</p><p>Fortunately, later, automatic tools became available, which could scan your dependencies and cross-check with vulnerability databases.</p><p><strong>Detection directly in your IDE</strong></p><p>Having a check for security vulnerabilities integrated as a part of your CI process is important and necessary, but it comes a bit late in the development pipeline.</p><p>It would be much better if you could check locally when adding a new dependency whether there are no security issues. This way, you could discover potential problems much earlier in the process. Snyk offers a CLI tool, which you can use, but for regular checking, it can be too cumbersome, and you have to remember to run it every time.</p><p>Fortunately, Snyk recently released also IntelliJ IDEA plugin, which monitors your dependencies and can show you security vulnerabilities directly in your IDE.</p><h4>Snyk plugin</h4><p>The plugin is available for free for both the Community and Ultimate editions.The <a href="https://plugins.jetbrains.com/plugin/10972-snyk-vulnerability-scanning">Snyk Plugin</a> is available directly from the plugin marketplace. You can access it using Settings → Plugins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*aEbL2HIPUzp8VSdT.png" /></figure><h4><strong>Once you install it and restart your IDE, a new tab is available:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1YthWTyRO3b1ee-a.png" /></figure><p>It shows all the dependencies with known security vulnerabilities, which your app uses. You can expand individual dependencies to explore the transitive dependencies, which introduce the vulnerability.</p><p>If there is a new version, which fixes the dependency, Snyk suggests a version to upgrade to, which is very useful. You can click the name of dependency, and Snyk automatically navigates you to the place, where it is declared in you pom.xml.</p><p>Finally, you can click the details link of each vulnerability, which navigates you to a web page in the Snyk vulnerability database with a detailed description of this particular vulnerability. You can then evaluate yourself how critical it is, what can you do to mitigate it a whether it applies in your case or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*g70JO3PMGKJR-1w3.png" /></figure><h4>Maven only</h4><p>Unfortunately, currently, the plugin supports only Maven and not Gradle. If you are using Gradle, you can stick With CLI or CI check, which does support it. However, according to Snyk, Gradle support is planned. Hopefully, it will be available soon.</p><h4>Conclusion</h4><p>Snyk IDEA plugin offers a simple, yet powerful way to detect security vulnerabilities in your dependencies directly in your IDE. This way, you can discover vulnerable libraries early in the development process without the need to wait for a Continuous Integration check. This, however, does not mean you should depend only on the plugin. You should still have CI check in place as a safeguard and continuous monitoring, which Snyk offers, to make sure you discover new vulnerabilities and their fixes once they are available.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44bb287affd0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/isop-nepal/detect-vulnerable-dependencies-in-intellij-idea-44bb287affd0">Detect vulnerable dependencies in IntelliJ IDEA</a> was originally published in <a href="https://medium.com/isop-nepal">ISOP Nepal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Admin SetUp]]></title>
            <link>https://medium.com/isop-nepal/spring-boot-admin-setup-8e5961bbea5d?source=rss-86d920e9d27------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e5961bbea5d</guid>
            <category><![CDATA[codecentric]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-boot-admin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot-actuator]]></category>
            <dc:creator><![CDATA[ISOP]]></dc:creator>
            <pubDate>Sun, 23 Jun 2019 04:30:29 GMT</pubDate>
            <atom:updated>2019-06-23T05:00:50.559Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Setup Spring Boot Admin?</h3><p>Recently I have setup Spring boot admin in my one of Project To Monitor and manage my Spring Boot apps with a nice UI on top of Spring Boot Actuator endpoints. Spring Boot admin really cool build on top of Spring boot Actuator.</p><h4>Spring Boot Actuator</h4><p>The actuator is a Spring Boot module, which adds REST/JMX endpoints to your application, so you can easily monitor and manage it in production. The endpoints offer health-check, metrics monitoring, access to logs, thread dumps, heap dumps, environmental info and more.</p><h4>Spring Boot Admin</h4><p>Spring Boot Admin is not a core module provided by the Spring team, it was made by a company called <a href="https://blog.codecentric.de/en/">concentric</a>. the code is publicly available on <a href="https://github.com/codecentric/spring-boot-admin">Github</a> and it is free.</p><p>The actuator is powerful and great and it is easy and convenient to consume the endpoints with some other application — you just make a simple REST call. It is not so great when used by a human. For humans, it is much more convenient to have a nice user interface you can use to browse all the monitoring data and manage your application. This is actually what Spring Boot Admin Does.</p><p><strong>Client And Server</strong>Spring Boot Admin actually comes in two parts — Client and Server.</p><p>The Server part contains the Admin user interface and runs independently from the monitored applications. The Client part is in the monitored application, which registers with the Admin Server part.</p><p>This way, even if our application is down or not working properly, the monitoring server is still up and running.</p><p>Now imagine you have multiple applications (such as Spring Boot microservices) and each of them can be running in multiple instances. With traditional Actuator monitoring, this is hard as you need to access each of them separately and you need to keep track of how many instances and where are running.</p><p>With Spring Boot Admin, each instance of your monitored application (Client) registers with the Server after it starts. Then you have a single point (Admin Server), where you can check them all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*n--96VjSjUbE7icU.png" /></figure><h4><strong>Server Setup</strong></h4><p>Let’s first look into how to set up the Spring Boot Admin Server. Let’s start with a fresh Spring Boot application. You can easily create one using <a href="https://start.spring.io/">Spring Initializr</a>. Be sure to include the webmodule.</p><p>After creating the project, the first thing we need is to add the Spring Boot Admin Server dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;de.codecentric&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-admin-starter-server&lt;/artifactId&gt;<br>    &lt;version&gt;2.1.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Next, we need to enable Admin Server by annotating our main application class with @EnableAdminServer:</p><pre>@SpringBootApplication<br>@EnableAdminServerpublic class SpringBootAdminServerApplication {<br><br>    public static void <strong>main</strong>(String[] args) {<br>        SpringApplication.<strong>run</strong>(SpringBootAdminServerApplication.class, args);<br>    }<br>}</pre><p>And that’s it. Now you can run your application and after opening http://localhost:8080/you should see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*p8yywydoa9svS5uO.png" /></figure><h4>Client Setup</h4><p>Same as with server setup, the first step is to add proper dependency to an existing application:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;de.codecentric&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-admin-starter-client&lt;/artifactId&gt;<br>    &lt;version&gt;2.1.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Then you need to define URL where is your Admin Server running. Add this line to your application.properties:</p><pre>spring.boot.admin.client.url=http://localhost:8080</pre><h4>Adding Actuator</h4><p>Now you should be able to run both the client and the server. Just make sure there is not a port conflict as both apps by default use 8080. For testing purposes, you can set server.port=0in your application.properties, so your client will use a random port on startup. This way you can test launching multiple instances running on different ports.</p><p>When you open Admin Server UI, you should see your application. When you click the app name, a page with application details should show up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*qwDPG24qE6pNI6L5.png" /></figure><p>If you see a screen like above with just a minimum of information, it means that you don’t have an Actuator as a part of your project. Remember, Spring Boot Admin uses Actuator endpoints under the hood. Fortunately, you need just to add a simple dependency and auto-configuration does take care of the rest.</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>However, most of the endpoints are not exposed by the Actuator by default. You need to change your configuration in application.properties to expose them:management.endpoints.web.exposure.include=*</p><p>After exposing your Actuator endpoints, you should see much more information in your Admin interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*2nLu7N2NA0v1nfI6.png" /></figure><h3>Server Security</h3><p>Same as with the client, we need to add Spring Security dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Now let&#39;s configure username and password required to login to the Admin Server in your application.properties:</p><pre>spring.security.user.name=admin<br>spring.security.user.password=admin-password</pre><p>Now in your <strong>Client,</strong> you need to add these credentials as well, otherwise, it will not be able to register with the server:</p><pre>spring.boot.admin.client.username=admin<br>spring.boot.admin.client.password=admin-password</pre><p>Now back to the <strong>Server</strong> part. The last thing we need is to add Spring Security configuration to protect the Admin user interface:</p><pre>@Configuration<br>public class SecurityConfig extends WebSecurityConfigurerAdapter {</pre><pre>    @Override<br>    protected void <strong>configure</strong>(HttpSecurity http) throws Exception {<br>        SavedRequestAwareAuthenticationSuccessHandler successHandler <br>            = new SavedRequestAwareAuthenticationSuccessHandler();<br>        successHandler.<strong>setTargetUrlParameter</strong>(&quot;redirectTo&quot;);<br>        successHandler.<strong>setDefaultTargetUrl</strong>(&quot;/&quot;);</pre><pre>        http.<strong>authorizeRequests</strong>()<br>            .<strong>antMatchers</strong>(&quot;/assets/**&quot;).<strong>permitAll</strong>()<br>            .<strong>antMatchers</strong>(&quot;/login&quot;).<strong>permitAll</strong>()<br>            .<strong>anyRequest</strong>().<strong>authenticated</strong>().<strong>and</strong>()<br>            .<strong>formLogin</strong>().<strong>loginPage</strong>(&quot;/login&quot;)<br>            .<strong>successHandler</strong>(successHandler).<strong>and</strong>()<br>            .<strong>logout</strong>().<strong>logoutUrl</strong>(&quot;/logout&quot;).<strong>and</strong>()<br>            .<strong>httpBasic</strong>().<strong>and</strong>()<br>            .<strong>csrf</strong>()<br>            .<strong>csrfTokenRepository</strong>(CookieCsrfTokenRepository.<strong>withHttpOnlyFalse</strong>())<br>            .<strong>ignoringAntMatchers</strong>(<br>                &quot;/instances&quot;,<br>                &quot;/actuator/**&quot;<br>             );<br>    }<br>}</pre><p>Now after a restart, you should see a nice login screen protecting your Admin Server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*qAfTO3adpiRaiGc2.png" /></figure><h3>Conclusion</h3><p>Spring Boot Admin offers a nice and useful UI layer on top of Actuator Endpoints. What’s more, it allows you to centrally monitor multiple applications with multiple instances, which is invaluable when working in the cloud and with microservices. Make sure though, that you sufficiently protect both your Client and Server. For further information, please check the <a href="http://codecentric.github.io/spring-boot-admin/current/">official documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e5961bbea5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/isop-nepal/spring-boot-admin-setup-8e5961bbea5d">Spring Boot Admin SetUp</a> was originally published in <a href="https://medium.com/isop-nepal">ISOP Nepal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Subscribe VS Async pipe in Angular]]></title>
            <link>https://medium.com/isop-nepal/subscribe-vs-async-pipe-in-angular-21bb38f3ee49?source=rss-86d920e9d27------2</link>
            <guid isPermaLink="false">https://medium.com/p/21bb38f3ee49</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[subscribe-vs-async-pipe]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[ISOP]]></dc:creator>
            <pubDate>Sat, 01 Jun 2019 17:47:32 GMT</pubDate>
            <atom:updated>2019-06-07T15:25:51.990Z</atom:updated>
            <content:encoded><![CDATA[<p>The Difference between the async pipe and Subscribe in Angular.</p><p><strong>I think we should always use async pipe when possible</strong> and <strong>only use </strong><strong>.subscribe when the side effect is an absolute necessity</strong>.</p><p>So today I would like to discuss and give explanations which I think will help in understanding when to use <strong>async pipe and </strong><strong>subscribe</strong></p><ol><li>Best practices</li><li>Observable and Rxjs</li><li>Subscribe function</li><li>Async pipe</li></ol><h3>Best practices</h3><p>To summarize, these are the best practices to ensure the validity of the logic:</p><ol><li>Prefer assignments rather than callbacks, assign Observable rather than subscription,</li><li>Let the framework terminate the Observable,</li><li>Leverage the power of Angular components and Angular async pipe to code without asynchronously,</li><li>Use libraries like reselect, rxjs to manipulate observable,</li><li>Make sure the external variables used inside the Rx operators function are const.</li></ol><h3>Observable and RxJS</h3><p>First, to understand the context, we need to understand what is observable.</p><h3>Observable</h3><p>Observable is an abstraction of an asynchronous stream of data.<br>For example, when we look at Observable&lt;string&gt;, it represents a stream of strings which will be delivered one by one over the time.</p><p><strong>Now, why would we care?</strong></p><p>We need to care because the stream of data coming in an asynchronous fashion is <strong>extremely</strong> hard to think about. And it is even harder when multiple streams need to be combined. It becomes very error prone to code around it.</p><p>To do such operations, we can use RxJS operators.</p><h3>RxJS</h3><p>RxJS operators, which can be found under add/operator, allow us to operate directly on observables, modifying, combining, aggregating, filtering data of observables.<strong>we are safe as long as we stay in the Observable.</strong></p><p>The power of RxJS is that each operation is assured to receive the output of the previous operation as its own input. This is an extremely powerful model that allows developers to easily follow the code logic making it predictable.</p><p>We must try to keep the observable as long as possible, combining it or modifying it using RxJS operators. As long as we stay within the observable, we do not need to think about the bigger picture.<br>All we need to think about is what to do with the single string we receive. We don’t need to care about the fact that we will receive multiple values over time hence the safety.</p><p>But if we keep the Observable modifying it around, how do we display data? This is where we have been used to .subscribe.</p><h3>Subscribe function</h3><p>We pass the observable around, combining it, saving it to different variables with different combinations of operators but at the end, an Observable&lt;T&gt; is useless on its own. We need a way to “terminate” the observable and extract the type T out of it. That is what .subscribe is used for. To subscribe to the resulting stream and terminate the observable.</p><p>Now we could do the following:</p><pre>costs: Cost[];<br><br>ngOnInit() {<br>    this.getCosts()<br>        .subscribe(costs =&gt; {<br>            this.costs = costs;<br>        });<br>}</pre><p>But as soon as it becomes more complex as if we need to get a list of Cost types to filter, it becomes hard to combine.</p><pre>costs: Cost[] = [];<br>filter = &quot;food&quot;;</pre><pre>ngOnInit() {<br>    this.getCosts()<br>        .subscribe(costs =&gt; {<br>            this.costs = costs.filter(e =&gt; e.type === this.filter);<br>        });</pre><pre>this.getFilter()<br>        .subscribe(filter =&gt; {<br>            this.filter = filter;<br>            this.costs = this.costs.filter(e =&gt; e.type === filter);<br>        });<br>}</pre><p>Now we can already appreciate the benefit of only subscribing when necessary and using them RxJS combinators:</p><pre>costs: Cost[] = [];</pre><pre>ngOnInit() {<br>    this.getCosts()<br>        .combineLatest(this.getFilter())<br>        .subscribe(([costs, filter]) =&gt; {<br>            this.costs = costs.filter(e =&gt; e.type === filter);<br>        });<br>}</pre><p>As mentioned earlier, we are safe from asynchronously as long as we stay in the observable therefore we can do even better and never actually use subscribe by using async pipe.</p><h3>Async Pipe</h3><p>In order to keep the observable, we would transform it as such:</p><pre>costs$: Observable&lt;Cost[]&gt;;</pre><pre>ngOnInit() {<br>    this.costs$ = this.getCosts()<br>        .combineLatest(this.getFilter())<br>        .map(([costs, filter]) =&gt; costs.filter(e =&gt; e.type === filter));<br>}</pre><p>The dollar $ is a convention to know that the variable is observable. Then to display from the UI, we would need to use the async pipe.</p><pre>{{ costs$ | async }}</pre><p>The other benefit of using the async pipe is that it shows us the way to decompose our UI into components. Because we want to remove the observable, we want to make a data binding using [costs]=&quot;{{ costs$ | async }}&quot; so that the component itself taking as input costs will be without observable. And this is the true beauty of the framework. By delaying the subscription till the end, we end up forcing ourselves in writing granular components that are abstracted from asynchronous.</p><h3>Conclusion</h3><p>Today we saw what was an Observable and how we could use leverage its power using RxJS. We also saw the differences between async pipe and subscription. Lastly, I shared my advice which is that <strong>we should always use async pipe when possible</strong> and <strong>only use </strong><strong>.subscribe when the side effect is an absolute necessity</strong> as <strong>we are safe as long as we stay in the observable</strong>. The code terminating the observable should be the framework (Angular) and the last piece (the UI). Hope you like this post, see you next time!</p><p>Today we saw what was an Observable and how we could power of RxJS. We additionally observed the contrasts between async pipe and subscription. In conclusion, I shared my recommendation which is that <strong>we should always use async pipe when possible</strong> and <strong>only use </strong><strong>.subscribe when the side effect is an absolute necessity</strong> as <strong>we are safe as long as we stay in the observable</strong>. The code terminating the observable should be the framework (Angular) and the last piece (the UI).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21bb38f3ee49" width="1" height="1" alt=""><hr><p><a href="https://medium.com/isop-nepal/subscribe-vs-async-pipe-in-angular-21bb38f3ee49">Subscribe VS Async pipe in Angular</a> was originally published in <a href="https://medium.com/isop-nepal">ISOP Nepal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coroutines in Kotlin]]></title>
            <link>https://medium.com/isop-nepal/coroutines-in-kotlin-da0d5cbacbc9?source=rss-86d920e9d27------2</link>
            <guid isPermaLink="false">https://medium.com/p/da0d5cbacbc9</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[ISOP]]></dc:creator>
            <pubDate>Fri, 24 May 2019 15:57:33 GMT</pubDate>
            <atom:updated>2019-05-24T15:57:33.901Z</atom:updated>
            <content:encoded><![CDATA[<p>In Mobile App, it’s essential to avoid blocking the main thread.</p><p>The main thread is a single thread that handles all updates to the UI. It’s also the thread that calls all click handlers and other UI callbacks. As such, it has to run smoothly to guarantee great user experience.</p><p>Many common tasks like parsing large JSON datasets, writing data to a database, or fetching data from the network takes longer time. Therefore, calling code from the main thread can cause the app to freeze. And if you block the main thread for too long, the app may even crash and present an Application Not Responding dialog.</p><p>One common example of performing a long-running task without blocking the main thread is callbacks pattern. By utilizing callbacks, we can begin a long-running task on a background thread. When the task completes, the callback is called to inform you of the result on the main thread.</p><p>Here is the Example of callback pattern:</p><pre><em>// Slow request with callbacks</em><br>@UiThread<br>fun performNetworkRequest() {<br>    <em>// The slow network request runs on another thread</em><br>    slowFetch { result -&gt;<br>        <em>// When the result is ready, this callback will get the result</em><br>        show(result)<br>    }<br>    <em>// </em>performNetworkRequest<em>() exits after calling slowFetch without waiting for the result</em><br>}</pre><p>This code is annotated with, <a href="https://developer.android.com/reference/android/support/annotation/UiThread">@UiThread</a> it must run fast enough to execute on the main thread. That means it needs to return very quickly so that the next screen update is not delayed. However, since slowFetch will take seconds or even minutes to complete, the main thread can&#39;t wait for the result. The show(result) callback allows slowFetch to run on a background thread and return the result when it&#39;s ready.</p><h3>Remove Callbacks Using Coroutines</h3><p>Kotlin coroutines let you convert callback-based code to sequential code. Code written sequentially is typically easier to read, and can even use language features such as exceptions.</p><p>In the end, they do the exact same thing: wait until a result is available from a long-running task and continue execution.</p><p>The keyword suspend is Kotlin&#39;s way of marking a function, or function type, available to coroutines. When a coroutine calls a function marked suspend, instead of blocking until that function returns like a normal function call, it suspends execution until the result is ready then it resumes where it left off with the result. While it&#39;s suspended waiting for a result, it unblocks the thread that it&#39;s running on so other functions or coroutines can run.</p><p>Callbacks are a great pattern, however, they have a few drawbacks. Code that heavily uses callbacks can become hard to read and harder to reason about. In addition, callbacks don’t allow the use of some language features, such as exceptions.</p><pre><em>// Slow request with coroutines</em><br>@UiThread<br>suspend fun performNetworkRequest() {<br>    <em>// slowFetch is another suspend function so instead of </em><br>    <em>// blocking the main thread  </em>performNetworkRequest<em> will ` . suspend` until the result is </em><br>    <em>// ready</em><br>    val result = slowFetch()<br>    <em>// continue to execute after the result is ready</em><br>    show(result)<br>}<br><br><em>// slowFetch is main-safe using coroutines</em><br>suspend fun slowFetch(): SlowResult { ... }</pre><p>The suspend keyword doesn&#39;t specify the thread code runs on. Suspend functions may run on a background thread or the main thread.</p><p>Compared to the callback-based code, coroutine code accomplishes the same result of unblocking the current thread with less code. Due to its sequential style, it’s easy to chain several long-running tasks without creating multiple callbacks. For example, code that fetches a result from two network endpoints and saves it to the database can be written as a function in coroutines with no callbacks.</p><pre><em>// Request data from network and save it to database with coroutines</em><br><br><em>// Because of the @WorkerThread, this function cannot be called on the</em><br><em>// main thread without causing an error.</em><br>@WorkerThread<br>suspend fun performNetworkRequest() {<br>    <em>// slowFetch and anotherFetch are suspend functions</em><br>    val slow = slowFetch()<br>    val another = anotherFetch()<br>    <em>// save is a regular function and will block this thread</em><br>    database.save(slow, another)<br>}<br><br><em>// slowFetch is main-safe using coroutines</em><br>suspend fun slowFetch(): SlowResult { ... }<br><em>// anotherFetch is main-safe using coroutines</em><br>suspend fun anotherFetch(): AnotherResult { ... }</pre><p>The pattern of async and await in other languages is based on coroutines. If you&#39;re familiar with this pattern, the suspend keyword is similar to async. However, in Kotlin, await() is implicit when calling a suspendfunction.</p><p>Kotlin has a method Deferred.await() that is used to wait for the result from a coroutine started with the async builder.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da0d5cbacbc9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/isop-nepal/coroutines-in-kotlin-da0d5cbacbc9">Coroutines in Kotlin</a> was originally published in <a href="https://medium.com/isop-nepal">ISOP Nepal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Useful Kotlin Extension Function]]></title>
            <link>https://medium.com/isop-nepal/useful-kotlin-extension-function-586c645c2020?source=rss-86d920e9d27------2</link>
            <guid isPermaLink="false">https://medium.com/p/586c645c2020</guid>
            <category><![CDATA[function]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[extension]]></category>
            <dc:creator><![CDATA[ISOP]]></dc:creator>
            <pubDate>Sun, 12 May 2019 22:24:45 GMT</pubDate>
            <atom:updated>2019-05-12T22:24:45.885Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFPh1J6BV1L3FeY_riwsYg.png" /></figure><p>Here is the collection of useful Kotlin Extension function that might speed your development. Just Make Extension.Kt Kotlin file copy and paste this code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFPh1J6BV1L3FeY_riwsYg.png" /></figure><pre><strong>fun </strong>ImageView.loadImageFromUrl(url: String) {<br>  Glide.with(<em>context</em>)<br>      .load(url)<br>      .into(<strong>this</strong>)<br>}<br><br><strong>fun </strong>Activity.hideKeyboard() {<br>  <strong>val </strong>imm = getSystemService(Context.<em>INPUT_METHOD_SERVICE</em>) <strong>as </strong>InputMethodManager<br>  imm.hideSoftInputFromWindow(<em>window</em>.<em>decorView</em>.<em>windowToken</em>, 0)<br>}<br><br><em>/**<br> * Extension method to remove the required boilerplate for running code after a view has been<br> * inflated and measured.<br> *<br> * </em><strong><em>@author </em></strong><em>Antonio Leiva<br> * </em><strong><em>@see </em></strong><em>&lt;a href=&quot;https://antonioleiva.com/kotlin-ongloballayoutlistener/&gt;Kotlin recipes: OnGlobalLayoutListener&lt;/a&gt;<br> */<br></em><strong>inline fun </strong>&lt;T : View&gt; T.afterMeasured(<strong>crossinline </strong>f: T.() -&gt; Unit) {<br>  <em>viewTreeObserver</em>.addOnGlobalLayoutListener(<strong>object </strong>: ViewTreeObserver.OnGlobalLayoutListener {<br>    <strong>override fun </strong>onGlobalLayout() {<br>      <strong>if </strong>(<em>measuredWidth </em>&gt; 0 &amp;&amp; <em>measuredHeight </em>&gt; 0) {<br>        <em>viewTreeObserver</em>.removeOnGlobalLayoutListener(<strong>this</strong>)<br>        f()<br>      }<br>    }<br>  })<br>}<br><br><em>/**<br> * Extension method to simplify the code needed to apply spans on a specific sub string.<br> */<br></em><strong>inline fun </strong>SpannableStringBuilder.withSpan(<strong>vararg </strong>spans: Any, action: SpannableStringBuilder.() -&gt; Unit):<br>    SpannableStringBuilder {<br>  <strong>val </strong>from = <strong>length<br>  </strong>action()<br><br>  <strong>for </strong>(span <strong>in </strong>spans) {<br>    setSpan(span, from, <strong>length</strong>, Spanned.<em>SPAN_EXCLUSIVE_EXCLUSIVE</em>)<br>  }<br><br>  <strong>return this<br></strong>}<br><br><em>/**<br> * Extension method to provide simpler access to {@link ContextCompat#getColor(int)}.<br> */<br></em><strong>fun </strong>Context.getColorCompat(color: Int) = ContextCompat.getColor(<strong>this</strong>, color)<br><br><em>/**<br> *  Extension method to provide simpler access to {@link ContextCompat#getColor(int)}<br> *  from a </em><strong><em>[Fragment]</em></strong><em>.<br> */<br></em><strong>fun </strong>Fragment.getColorCompat(color: Int) = <em>context</em>?.<em>getColorCompat</em>(color)<br><br><em>/**<br> * Extension method to provide simpler access to {@link ContextCompat#getDrawableCompat(int)}.<br> */<br></em><strong>fun </strong>Context.getDrawableCompat(drawableResId: Int): Drawable? = ContextCompat<br>    .getDrawable(<strong>this</strong>, drawableResId)<br><br><em>/**<br> * Extension method to provide simpler access to {@link ContextCompat#getDrawableCompat(int)}<br> * from a </em><strong><em>[Fragment]</em></strong><em>.<br> */<br></em><strong>fun </strong>Fragment.getDrawableCompat(drawableResId: Int) = <em>context</em>?.<em>getDrawableCompat</em>(drawableResId)!!<br><br><em>/**<br> * Extension method to provide simpler access to {@link View#getResources()#getString(int)}.<br> */<br></em><strong>fun </strong>View.getString(stringResId: Int): String = <em>resources</em>.getString(stringResId)<br><br><em>/**<br> * Extension method to provide show keyboard for View.<br> */<br></em><strong>fun </strong>View.showKeyboard() {<br>  <strong>val </strong>imm = <em>context</em>.getSystemService(Context.<em>INPUT_METHOD_SERVICE</em>) <strong>as </strong>InputMethodManager<br>  <strong>this</strong>.requestFocus()<br>  imm.showSoftInput(<strong>this</strong>, 0)<br>}<br><br><em>/**<br> * Extension method to provide hide keyboard for </em><strong><em>[Activity]</em></strong><em>.<br> */<br></em><strong>fun </strong>Activity.hideSoftKeyboard() {<br>  <strong>if </strong>(<em>currentFocus </em>!= <strong>null</strong>) {<br>    <strong>val </strong>inputMethodManager = getSystemService(Context<br>        .<em>INPUT_METHOD_SERVICE</em>) <strong>as </strong>InputMethodManager<br>    inputMethodManager.hideSoftInputFromWindow(<em>currentFocus</em>!!.<em>windowToken</em>, 0)<br>  }<br>}<br><br><em>/**<br> * Extension method to provide hide keyboard for </em><strong><em>[Fragment]</em></strong><em>.<br> */<br></em><strong>fun </strong>Fragment.hideSoftKeyboard() {<br>  <em>activity</em>?.<em>hideSoftKeyboard</em>()<br>}<br><br><em>/**<br> * Extension method to provide hide keyboard for </em><strong><em>[View]</em></strong><em>.<br> */<br></em><strong>fun </strong>View.hideKeyboard() {<br>  <strong>val </strong>imm = <em>context</em>.getSystemService(Context.<em>INPUT_METHOD_SERVICE</em>) <strong>as </strong>InputMethodManager<br>  imm.hideSoftInputFromWindow(<em>windowToken</em>, 0)<br>}<br><br><em>/**<br> * Extension method to int time to 2 digit String<br> */<br></em><strong>fun </strong>Int.twoDigitTime() = <strong>if </strong>(<strong>this </strong>&lt; 10) <strong>&quot;0&quot; </strong>+ toString() <strong>else </strong>toString()<br><br><em>/**<br> * Extension method to provide quicker access to the </em><strong><em>[LayoutInflater]</em></strong><em> from </em><strong><em>[Context]</em></strong><em>.<br> */<br></em><strong>fun </strong>Context.getLayoutInflater() = getSystemService(Context.<em>LAYOUT_INFLATER_SERVICE</em>) <strong>as </strong>LayoutInflater<br><br><em>/**<br> * Extension method to provide quicker access to the </em><strong><em>[LayoutInflater]</em></strong><em> from a </em><strong><em>[View]</em></strong><em>.<br> */<br></em><strong>fun </strong>View.getLayoutInflater() = <em>context</em>.<em>getLayoutInflater</em>()<br><br><em>/**<br> * Extension method to replace all text inside an </em><strong><em>[Editable]</em></strong><em> with the specified </em><strong><em>[newValue]</em></strong><em>.<br> */<br></em><strong>fun </strong>Editable.replaceAll(newValue: String) {<br>  replace(0, <strong>length</strong>, newValue)<br>}<br><br><em>/**<br> * Extension method to replace all text inside an </em><strong><em>[Editable]</em></strong><em> with the specified </em><strong><em>[newValue]</em></strong><em> while<br> * ignoring any </em><strong><em>[android.text.InputFilter]</em></strong><em> set on the </em><strong><em>[Editable]</em></strong><em>.<br> */<br></em><strong>fun </strong>Editable.replaceAllIgnoreFilters(newValue: String) {<br>  <strong>val </strong>currentFilters = <em>filters<br>  filters </em>= <em>emptyArray</em>()<br>  <em>replaceAll</em>(newValue)<br>  <em>filters </em>= currentFilters<br>}<br><br><em>/**<br> * Extension method to cast a char with a decimal value to an </em><strong><em>[Int]</em></strong><em>.<br> */<br></em><strong>fun </strong>Char.decimalValue(): Int {<br>  <strong>if </strong>(!<em>isDigit</em>())<br>    <strong>throw </strong>IllegalArgumentException(<strong>&quot;Out of range&quot;</strong>)<br>  <strong>return this</strong>.toInt() - <strong>&#39;0&#39;</strong>.toInt()<br>}<br><br><em>/**<br> * Extension method to simplify view binding.<br> */<br></em><strong>fun </strong>&lt;T : ViewDataBinding&gt; View.bind() = DataBindingUtil.bind&lt;T&gt;(<strong>this</strong>) <strong>as </strong>T<br><br><em>/**<br> * Extension method to simplify view inflating and binding inside a </em><strong><em>[ViewGroup]</em></strong><em>.<br> *<br> * e.g.<br> * This:<br> *&lt;code&gt;<br> *     binding = bind(R.layout.widget_card)<br> *&lt;/code&gt;<br> *<br> * Will replace this:<br> *&lt;code&gt;<br> *     binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.widget_card, this, true)<br> *&lt;/code&gt;<br> */<br></em><strong>fun </strong>&lt;T : ViewDataBinding&gt; ViewGroup.bind(layoutId: Int): T {<br>  <strong>return </strong>DataBindingUtil.inflate(<em>getLayoutInflater</em>(), layoutId, <strong>this</strong>, <strong>true</strong>)<br>}<br><br><strong>fun </strong>&lt;T : ViewDataBinding&gt; Activity.bind(layoutId: Int): T {<br>  <strong>return </strong>DataBindingUtil.setContentView(<strong>this</strong>, layoutId)<br>}<br><br><strong>fun </strong>String.dateInFormat(format: String): Date? {<br>  <strong>val </strong>dateFormat = SimpleDateFormat(format, Locale.<em>US</em>)<br>  <strong>var </strong>parsedDate: Date? = <strong>null<br>  try </strong>{<br>    parsedDate = dateFormat.parse(<strong>this</strong>)<br>  } <strong>catch </strong>(ignored: ParseException) {<br>    ignored.printStackTrace()<br>  }<br>  <strong>return </strong>parsedDate<br>}<br><br><strong>fun </strong>getClickableSpan(color: Int, action: (view: View) -&gt; Unit): ClickableSpan {<br><br>  <strong>return object </strong>: ClickableSpan() {<br>    <strong>override fun </strong>onClick(view: View) {<br>      action(view)<br>    }<br><br>    <strong>override fun </strong>updateDrawState(ds: TextPaint) {<br>      <strong>super</strong>.updateDrawState(ds)<br>      ds.<em>color </em>= color<br>    }<br>  }<br>}<br><br><em>/**<br> * Extension method to be used as the body for functions that are not yet implemented, which will<br> * display a </em><strong><em>[Toast]</em></strong><em> with the specified </em><strong><em>[message]</em></strong><em>.<br> */<br></em><strong>fun </strong>Fragment.NOT_IMPL(message: String = <strong>&quot;This action is not implemented yet!&quot;</strong>) {<br>  <em>TOAST</em>(message)<br>}<br><br><em>/**<br> * Extension method used to display a </em><strong><em>[Toast]</em></strong><em> message to the user.<br> */<br></em><strong>fun </strong>Fragment.TOAST(message: String, duration: Int = Toast.<em>LENGTH_SHORT</em>) {<br>  Toast.makeText(<em>context</em>, message, duration).show()<br>}<br><br><em>/**<br> * Extension method used to display a </em><strong><em>[Toast]</em></strong><em> message to the user.<br> */<br></em><strong>fun </strong>Fragment.TOAST(messageResId: Int, duration: Int = Toast.<em>LENGTH_SHORT</em>) {<br>  Toast.makeText(<em>context</em>, messageResId, duration).show()<br>}<br><br><em>/**<br> * Extension method use to display a </em><strong><em>[Snackbar]</em></strong><em> message to the user.<br> */<br></em><strong>fun </strong>View.displaySnakbar(message: String, duration: Int = Snackbar.<em>LENGTH_SHORT</em>): Snackbar {<br>  <strong>val </strong>snakbar = Snackbar.make(<strong>this</strong>, message, duration)<br>  snakbar.show()<br>  <strong>return </strong>snakbar<br>}<br><br><em>/**<br> * Extension method use to display a </em><strong><em>[Snackbar]</em></strong><em> message to the user.<br> */<br></em><strong>fun </strong>View.displaySnakbar(messageResId: Int, duration: Int = Snackbar.<em>LENGTH_SHORT</em>): Snackbar {<br>  <strong>val </strong>snakbar = Snackbar.make(<strong>this</strong>, messageResId, duration)<br>  snakbar.show()<br>  <strong>return </strong>snakbar<br>}<br><br><em>/**<br> * Extension method to return the view location on screen as a </em><strong><em>[Point]</em></strong><em>.<br> */<br></em><strong>fun </strong>View.locationOnScreen(): Point {<br>  <strong>val </strong>location = IntArray(2)<br>  getLocationOnScreen(location)<br>  <strong>return </strong>Point(location[0], location[1])<br>}<br><br><em>/**<br> * Extension method to return the view location in window as a </em><strong><em>[Point]</em></strong><em>.<br> */<br></em><strong>fun </strong>View.locationInWindow(): Point {<br>  <strong>val </strong>location = IntArray(2)<br>  getLocationInWindow(location)<br>  <strong>return </strong>Point(location[0], location[1])<br>}<br><br><em>/**<br> * Extension method used to return the value of the specified float raised to the power<br> * of the specified </em><strong><em>[exponent]</em></strong><em>.<br> */<br></em><strong>fun </strong>Float.pow(exponent: Float) = Math.pow(<strong>this</strong>.toDouble(), exponent.toDouble()).toFloat()<br><br><em>/**<br> * Extension method to provide show keyboard for View.<br> */<br></em><strong>fun </strong>View.gone() {<br>  <strong>if </strong>(<em>visibility </em>!= View.<em>GONE</em>) {<br>    <em>visibility </em>= View.<em>GONE<br>  </em>}<br>}<br><br><em>/**<br> * Extension method to provide show keyboard for View.<br> */<br></em><strong>fun </strong>View.visible() {<br>  <strong>if </strong>(<em>visibility </em>!= View.<em>VISIBLE</em>) {<br>    <em>visibility </em>= View.<em>VISIBLE<br>  </em>}<br>}<br><br><em>/**<br> * Convert a </em><strong><em>[Boolean]</em></strong><em> value to a view visibility </em><strong><em>[Int]</em></strong><em>.<br> */<br></em><strong>fun </strong>Boolean.toViewVisibility(valueForFalse: Int = View.<em>GONE</em>): Int {<br>  <strong>return if </strong>(<strong>this</strong>) {<br>    View.<em>VISIBLE<br>  </em>} <strong>else </strong>{<br>    valueForFalse<br>  }<br>}<br><br><em>/**<br> * Method used to easily retrieve </em><strong><em>[WindowManager]</em></strong><em> from </em><strong><em>[Context]</em></strong><em>.<br> */<br></em><strong>fun </strong>Context.getWindowManager() = getSystemService(Context.<em>WINDOW_SERVICE</em>) <strong>as </strong>WindowManager<br><br><em>/**<br> * Method used to easily retrieve display size from </em><strong><em>[Context]</em></strong><em>.<br> */<br></em><strong>fun </strong>Context.getDisplaySize() = Point().<em>apply </em><strong>{<br>  </strong><em>getWindowManager</em>().<em>defaultDisplay</em>.getSize(<strong>this</strong>)<br><strong>}<br><br></strong><em>/**<br> * Method used to easily retrieve display size from </em><strong><em>[View]</em></strong><em>.<br> */<br></em><strong>fun </strong>View.getDisplaySize() = <em>context</em>.<em>getDisplaySize</em>()<br><br><em>/**<br> * Provide the ability to snap to a specified </em><strong><em>[position]</em></strong><em> in the specified </em><strong><em>[recyclerView]<br> </em></strong><em>* using </em><strong><em>[SnapHelper]</em></strong><em>.<br> */<br></em><strong>fun </strong>SnapHelper.snapToPosition(recyclerView: RecyclerView, position: Int) {<br>  recyclerView.<em>apply </em><strong>{<br>    val </strong>view = findViewHolderForAdapterPosition(position)?.<strong>itemView<br>    val </strong>snapPositions = view?.<em>let </em><strong>{<br>      </strong><em>layoutManager</em>?.<em>let </em><strong>{ </strong>it1 <strong>-&gt; </strong>calculateDistanceToFinalSnap(it1, <strong>it</strong>) <strong>}<br>    }<br><br>    </strong>snapPositions?.<em>let </em><strong>{ </strong>smoothScrollBy(<strong>it</strong>[0], <strong>it</strong>[1]) <strong>}<br>  }<br></strong>}<br><br><em>/**<br> * Return whether Keyboard is currently visible on screen or not.<br> *<br> * </em><strong><em>@return </em></strong><em>true if keyboard is visible.<br> */<br></em><strong>fun </strong>Activity.isKeyboardVisible(): Boolean {<br>  <strong>val </strong>r = Rect()<br><br>  <em>//r will be populated with the coordinates of your view that area still visible.<br>  window</em>.<em>decorView</em>.getWindowVisibleDisplayFrame(r)<br><br>  <em>//get screen height and calculate the difference with the usable area from the r<br>  </em><strong>val </strong>height = <em>getDisplaySize</em>().<strong>y<br>  val </strong>diff = height - r.<strong>bottom<br><br>  </strong><em>// If the difference is not 0 we assume that the keyboard is currently visible.<br>  </em><strong>return </strong>diff != 0<br>}<br><br><em>/**<br> * Provides simpler access to the </em><strong><em>[ViewTreeObserver]</em></strong><em> inside a fragment.<br> *<br> * </em><strong><em>@return </em></strong><em>the </em><strong><em>[ViewTreeObserver]</em></strong><em> of the </em><strong><em>[Activity]</em></strong><em> this fragment currently attached to, or null<br> * if the fragment is detached.<br> */<br></em><strong>fun </strong>Fragment.getViewTreeObserver() = <em>activity</em>?.<em>window</em>?.<em>decorView</em>?.<em>viewTreeObserver<br><br>/**<br> * Extension method to set width for View.<br> */<br></em><strong>fun </strong>View.setWidth(value: Int) {<br>  <strong>val </strong>lp = <em>layoutParams<br>  </em>lp?.<em>let </em><strong>{<br>    </strong>lp.<strong>width </strong>= value<br>    <em>layoutParams </em>= lp<br>  <strong>}<br></strong>}<br><br><em>/**<br> * Extension method to display Width for Context.<br> */<br></em><strong>fun </strong>Context.displayWidth(): Int = <em>getDisplaySize</em>().<strong>x<br><br></strong><em>/**<br> * Retrieve a decoded bitmap from resources, or null if the image could not be decoded.<br> */<br></em><strong>fun </strong>Context.decodeBitmap(resId: Int): Bitmap? = BitmapFactory.decodeResource(<em>resources</em>, resId)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=586c645c2020" width="1" height="1" alt=""><hr><p><a href="https://medium.com/isop-nepal/useful-kotlin-extension-function-586c645c2020">Useful Kotlin Extension Function</a> was originally published in <a href="https://medium.com/isop-nepal">ISOP Nepal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>