<?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 ömer iyiöz on Medium]]></title>
        <description><![CDATA[Stories by ömer iyiöz on Medium]]></description>
        <link>https://medium.com/@omeriyioz?source=rss-830264dd5efb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-0mN92Ls5Tn6nGicSpSuCg@2x.jpeg</url>
            <title>Stories by ömer iyiöz on Medium</title>
            <link>https://medium.com/@omeriyioz?source=rss-830264dd5efb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 08:31:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omeriyioz/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[From Zero To Hero Series ( Kotlin Sequences, Channels, Flows ) — Part 3 — Flows]]></title>
            <link>https://medium.com/digigeek/from-zero-to-hero-series-kotlin-sequences-channels-flows-part-3-flows-5cdb391295b8?source=rss-830264dd5efb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cdb391295b8</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[ömer iyiöz]]></dc:creator>
            <pubDate>Mon, 05 Jul 2021 08:57:40 GMT</pubDate>
            <atom:updated>2021-07-09T05:16:11.796Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/digigeek/from-zero-to-hero-series-kotlin-sequences-channels-flows-part-1-sequences-3dbba97f55c2?source=your_stories_page-------------------------------------">From Zero To Hero Series</a> ( Kotlin Sequences, Channels, Flows ) — Part 3 — Flows</h3><p>We will learn Kotlin flows with 29 examples in this lesson. This will be a long journey. 🏄‍♂️</p><p>I hear, you say to me “Talk is cheap, show me the code”. Then let me start flowing 🌊🌊🌊 !</p><p><strong>Flow Example 1</strong></p><pre><em>To get all the values in the stream as they&#39;re emitted, use collect().</em></pre><p>Look at the following example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmHjVqOPqWKah7WMT_zmsQ.png" /></figure><p>From this example, we understand the followings :</p><ul><li>When we called <strong>flow{ } </strong>,</li></ul><pre>flow {<br>    <em>// the code inside the flow{} is not called.<br></em>}</pre><ul><li>When we called <strong>flow.collect{} </strong>,</li></ul><pre>flow {<br>    <em>// the code inside the flow{} is called.<br></em>}</pre><p><strong>In other words, we understand that “flows are cold streams”.</strong></p><p>Why we need <strong>runBlocking{}</strong> in this example ?</p><blockquote>Since <em>collect()</em> is a suspending function, it can only be called from a coroutine context. runBlocking{ } provides us a coroutine context, thus we used it in this example.</blockquote><p>In this example, we used collect() . collect() is the most basic terminal operator. There are also other terminal operators available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fq4v3_HaHvkimhsNhTDfRA.png" /></figure><p>Read the timeline which is shown in the above screenshot from top to below.</p><ul><li>Collector invokes the emitter.</li><li>Emitter emits value.</li><li>Collector’s lambda method runs.</li><li>Emitter emits value.</li><li>Collector’s lambda method runs.</li><li>Since emission ends in emitter, emitter says to collector “i’m finished”.</li></ul><p>Note : Emitter does not start until collect(or any other terminal operator) of collector runs.</p><p>As you understand, collector functions calling back and forth. In other words,</p><ul><li>one emission occurs and collector’s lambda is called ,</li><li>then one emission occurs and collector’s lambda is called,</li><li>then one emission occurs and collector’s lambda is called,</li><li>and so on..</li></ul><p><strong>BackPressure</strong></p><p>Backpressure is a term in reactive streams which describes the behavior when consumer is not consuming events that fast as producer produces them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlRAhD09Lrwmg0tNl6WDpQ.png" /></figure><p>Collector and emitter can be asynchronous.</p><p>While collector is suspended waiting for something, e.g. delays 100 miliseconds as in the above example, emitter waits and does not emit anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*bGrsbHg97KdAON2zV43cTg.png" /></figure><p>In above picture, each person waiting in the queue represents an emission. If our collector is slow, it slows down the emitter. Thus, each emission wait its turn. There is no special magic to implement this. It just happens automatically because of the nature of suspending function and the fact that our function calls back and forth.</p><p><strong>Flow Example 2</strong></p><p>In this example we launched a coroutine and flow. <strong>launch()</strong> and <strong>collect()</strong> not block eachother. Since collect is a suspending function, println(“end”) is not called until <strong>collect()</strong> function ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JkbX5cblihXzrD5Caci-vQ.png" /></figure><p><strong>Flow Example 3 — collect() and withTimeoutOrNull()</strong></p><p>In this example, we collect the stream inside <strong>withTimeoutOrNull()</strong>. Only two values is emitted and timeout occurs. Thus 3rd value is not emitted in this sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*pY9LG8kH4P_p5oun0atrNw.png" /></figure><p><strong>Flow example 4 — asFlow()</strong></p><p>Various collections and sequences can be converted to flows using <strong>asFlow()</strong> extension functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0xM5Tb0Q23lmMbLZFamlg.png" /></figure><p><strong>Flow example 5 — Intermediate Flow Operators</strong></p><blockquote>Flows can be transformed with operators, just as you would with collections and sequences. Intermediate operators are applied to an upstream flow and return a downstream flow. These operators are cold, just like flows are. A call to such an operator is not a suspending function itself. It works quickly, returning the definition of a new transformed flow.</blockquote><blockquote>The important difference to sequences is that blocks of code inside these operators can call suspending functions.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_P-j0TzvrtnU6s9M6iMFg.png" /></figure><p><strong>Flow Example 6 — Transform operator</strong></p><p><strong>transform() </strong>operator is used to imitate simple transformations like <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/map.html">map</a> and <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/filter.html">filter</a>, as well as implement more complex transformations. Using the transform operator, we can <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow-collector/emit.html">emit</a> arbitrary values an arbitrary number of times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBQeTqSFT82_KfTvBvY3_Q.png" /></figure><p><strong>Flow example 7 — Size limiting operators, such as take() function</strong></p><blockquote>Cancellation in coroutines is always performed by throwing an exception.</blockquote><p>When the corresponding limit is reached, <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/take.html"><strong>take</strong></a><strong>()</strong> function cancels the execution of the flow . Thus coroutine throws an exception. If you want to handle exception, you can write <strong>try catch finally</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBV8hsehkiEnDmEdnbqWYQ.png" /></figure><p><strong>Flow example 8 — Terminal flow operator reduce</strong></p><p>Remember that you must use a terminal operator to start a flow. Until now, we only used one terminal operator :</p><pre><strong>collect</strong></pre><p>Some of other terminal operators are the following :</p><pre><strong>first, single, reduce, fold</strong></pre><p>Look at the following example which uses <strong>reduce</strong> terminal operator. Let’s analyze how sum1 is found.</p><p>flow emits 1,2,3,4,5. reduce makes addition of 1 and 2 and gives the result of 3 as operand to the next addition operation. reduce makes addition of 3 and 3 and gives the result of 6 as operand to the next addition operation. reduce makes addition of 6 and 4 and gives the result of 10 as operand to the next addition operation. reduce makes addition of 10 and 5 and returns the result as 15.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNnOpjRouSIK9QuV3_8mYw.png" /></figure><p><strong>Flow Example 9 — Flows are sequential 🦖</strong></p><p>Each emission of a flow is performed sequentially unless special operators that operate on multiple flows are used. For example, in the below example, the order of emissions is 1,2,3,4,5.</p><p>Each emitted value is processed by all the intermediate operators from upstream to downstream and is then delivered to the terminal operator after.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NHqruc3QnBydXOzTeCg4A.png" /></figure><p><strong>Flow Example 10 — Flow context and <em>context preservation 🚓</em></strong></p><p>flow and collector function runs in the context which <strong>collect()</strong> function is called. This property of a flow is called <strong><em>context preservation</em></strong>.</p><p>In the below example, <strong>collect() </strong>function is called inside the main thread, so flow and collector function runs in the main thread too.</p><p>If you call <strong>collect()</strong> function inside IO dispatcher context, then flow and collector runs in IO dispatcher context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uZmiX3-DFxri8YxOl0pcw.png" /></figure><p>If collect() is called in main thread context, then updateUI() is called in main thread too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*_nUtzGidy0aGn193KFDqwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kAjex1KeywLM9BmPaolDOw.png" /></figure><p>What if my collector is on the main thread, but my computation contains an intensive work thus flow should not be run on main thread. If so, i can call <strong>flowOn(Dispatchers.Default)</strong> operator so that it changes the execution context as background thread for the preceding code. However my collector’s lambda function still runs in the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBlsO8f6-pbYL1PpiMFLhg.png" /></figure><p><strong>Flow Example 11 — Wrong emission withContext</strong></p><p>withContext() is called to change coroutine context.</p><p>In the following example, collect() is called in main thread. We called the withContext() to change the coroutine context to default dispatcher thread and try to emit a value inside dispatcher thread. Exception occurs in this case because the code in the flow { ... } builder has to honor the context preservation property and is not allowed to <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow-collector/emit.html">emit</a> from a different context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XfnvIdIHoSIrTWv0H1F0eg.png" /></figure><p>If you want to safely change the context of the flow emission, you should use <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flow-on.html"><strong>flowOn</strong></a> function.</p><p><strong>Flow Example 12 — Safely change the context of flow emission using flowOn() function</strong></p><p><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flow-on.html">flowOn</a>() function should be used to change the context of the flow emission.</p><p>In the following example, we explicitly specify the flow context by calling</p><pre><em>flowOn</em>(Dispatchers.<strong>Default</strong>)</pre><p>Thus, flow runs in the default dispatcher context, although collection happens in the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpuJqjFOY-pCHFthY4Necg.png" /></figure><p>The equivalent of flowOn() function is subscribeOn() function in RxJava.</p><p><strong>Flow Example 13 — Buffer</strong></p><p>In order to understand buffering, firstly we analyze the following flow exam which does not use buffering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D21fIg6V3AKZPx2JDKfeFQ.png" /><figcaption>Flow example without buffering</figcaption></figure><p>In this example, Three integer value will be emitted inside flow. However, 1 second delay occurs before emitting. Furthmore, 5 second delay occurs in the collector. Lets analyze step by step:</p><ul><li>When we called collect, flow starts to run. and 1 second delay occurs. After 1 second delay finishes, value 1 is emitted.</li><li>Collect is invoked with value 1, and 5 second delay occurs in collector. Since we do not use buffering, flow does not continue to work and waits for collector completes for value 1. After 5 second delay finishes, flow can continue to work for value 2. 1 second delay occurs.</li><li>After 1 second delay finishes, collect is invoked with value 2. 5 minute delay occurs and flow cannot continue and wait for collector completes for value 2 since we do not use buffering. After 5 second delay finishes, flow can continue to work for value 3. 1 second delay occurs.</li><li>After 1 second delay finishes, collect is invoked with value 3. 5 minute delay occurs and flow cannot continue and wait for collector completes for value 3 since we do not use buffering. After 5 second delay finishes, collector completes its work.</li></ul><p>Now, let’s do an example using buffering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrEnIca8kXrP1rxBfNB_yQ.png" /><figcaption>Flow example with buffering</figcaption></figure><p>The only difference in this example from the previous one is that we called buffer() method.</p><p>What does buffer() method provide us? It provides us that flow and collector runs concurrently. For example if a delay occurs in collector, flow continue its work and does not wait collector.</p><p>In the first example which does not use buffering, flow and collector runs sequentially.</p><p>Lets analyze the example,</p><p>Value 1 is emitted inside flow. So Collector is invoked and collector is delayed for 5 second. Flow does not wait the <em>finish of collector’s delay,</em> thus value 2 is emitted. Collector is still in delay for value 1. Value 3 is emitted in flow, and flow completes. Collector is still in delay for value 1. As you see flow emits 3 value and does not wait completion of collector for each emission. After some time, collector finishes its work for value 1, then delays 5 second, finishes it work for value 2, then delays 5 second, finishes it work for value 3.</p><p>As you see, the emission of flows are processed by collector in the first in first out order.</p><p>Notice that, each emission is processed when you use buffer() method.</p><p><strong>Flow Example 14 — Conflation</strong></p><p>Conflation is one way to speed up processing when both the emitter and collector are slow. It does it by dropping emitted values if emisson does not start to be processed by collector, it collects last unprocessed emission. The emissions in progress does not affect from this, and continue until completion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJe4dn7zSiE32Elxrm5XXQ.png" /><figcaption>Flow example with using conflate()</figcaption></figure><p>In this example, flow 1 is emitted and collector starts to process this emission. Collector delays 5 second. Before the delay of the collector doesn’t finish, flow makes 2 emissions, and done its work. When collector process the emission for value 1, there is 2 emission waiting in the queue. Since we use conflation, collector drop the emission for value 2, and starts to process the emission for value 3.</p><p>To sum up, conflation is a type of buffering. However, collector does not process all emissions.</p><ul><li>flow and collector runs concurrently.</li><li>If a collection collected an emission and started proccessing, it continues until completion.</li><li>When collector is available to work, if there are more than one emission which does not started to process in collector, only the latest emission processed. The old emissions which has not collected are dropped.</li></ul><h3>Flow Example 15 — collectLatest — Processing the latest value</h3><p>Conflation is one way to speed up processing when both the emitter and collector are slow. It does it by dropping emitted values. The other way is to cancel a slow collector and restart it every time when a new value is emitted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVTXV-Wcbyuesh-3K51NoA.png" /><figcaption>Flow example with using collectLatest</figcaption></figure><p>In this example,</p><ul><li>when collectLatest is called, flow starts to run, delays 1 second, and emit value 1, then delays 1 second too.</li><li>Collector collects the emission for value 1 and delays 5 second.</li><li>Then flow emits value 2. At this point, collector does not complete processing for value 1, but since a new emission comes and we used collectLatest, collector cancels processing for value 1, collects value 2, starts to process it, delay 5 second.</li><li>Then flow emits again a new value 3. At this point, collector does not complete processing for value 2, but since a new emission comes and we used collectLatest, collector cancels processing for value 2, collects value 3, starts to process it, delay 5 second. <strong>Collector completes its work only for the last emission for value 3. Collector cancel its processing for the other two emissions for value 1 and 2.</strong></li></ul><p>To sum up, when flow emits a new value, if the collector is busy with processing an old emission it cancels processing of the old emission, collects the new emisson and starts to process it.</p><p><strong>Summary of difference between buffer(), conflate(), collectLatest().</strong></p><p>They all provides us that flow and collector runs concurrently.</p><p><strong>buffer() :</strong></p><ul><li>All emissions made by flow is collected and processed until completion.</li></ul><p><strong>conflate() :</strong></p><ul><li>If a collection started processing an emission it continues until completion.</li><li>When collector is available to work, if there are more than one emission which does not started to process in collector, only the latest emission processed. The old emissions which has not collected yet are dropped.</li></ul><p><strong>collectLatest :</strong></p><ul><li>Assume that a collection started processing an emission. Before completion of the processing of this emission, if a new emission occurs, collector cancels the processing of current work, collects the latest value, and starts to process it.</li></ul><p><strong>Flow Example 16 — onEach</strong></p><pre>fun foo20(): Flow&lt;Int&gt; = <em>flow </em><strong>{<br>    </strong>for (i in 1..3) {<br>        delay(1000)<br>        emit(i)<br>    }<br><strong>}</strong></pre><pre>fun main() = <em>runBlocking</em>&lt;Unit&gt; <strong>{</strong></pre><pre><strong>    </strong><em>foo20</em>()<br>        .collect <strong>{<br>            </strong><em>println</em>(<strong>it</strong>)<br>        <strong>}</strong><em><br></em><strong>}</strong></pre><p>We can write foo20() function shown in above code example, as the following using the onEach().</p><pre>fun main() = <em>runBlocking</em>&lt;Unit&gt; <strong>{</strong></pre><pre><strong>    </strong>val numbersFlow = (1..3).<em>asFlow</em>().<em>onEach </em><strong>{ </strong>delay(1000) <strong>}</strong></pre><pre><em>    </em>numbersFlow<br>        .collect <strong>{<br>            </strong><em>println</em>(<strong>it</strong>)<br>        <strong>}<br>}</strong></pre><p>Output :</p><pre><strong>1<br>2<br>3</strong></pre><p>onEach function is called for each emission. There is no need to call emit() inside onEach. numbersFlow will emit 3 values, for each emission delays 1 second, then emit the value.</p><h3>Composing multiple flows</h3><p>There are lots of ways to compose multiple flows.</p><p><strong>Flow Example 17 — zip</strong></p><p>Flows have <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/zip.html"><strong>zip</strong></a> and <strong>combine</strong> operator that combines the corresponding values of two flows. There is an important difference between these two operator. Let me explain, firstly with zip() operator.</p><p>Just like the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/zip.html">Sequence.zip</a> extension function in the Kotlin standard library, flows have a <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/zip.html">zip</a> operator that combines the corresponding values of two flows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1qTFG54ufjvq_TLIMY3Bg.png" /></figure><p><strong>Another zip example</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OlMjFSaXUH_rED-JtKeWg.png" /></figure><p>Zip operator waits for 2 flow to emit value to continue execution. In this example, 2nd flow is 40 times faster than 1st flow.</p><ul><li>1st flow delays execution 100 ms, then emit value 1, then suspended until second flow emits value. 2nd flow delays 4000 ms, in this time, zip operator and 1st flow do nothing, wait for emission of 2nd flow. 2nd flow emits value. At this point, since 2 flow has emitted value, zip can continue execution from now on. Thus, map function works.</li><li>2nd flow delays execution 100 ms with value 2, then emit, then waits without doing nothing. 3rd from delays 4000ms, then emit value, At this point, since 2 flow has emitted value, zip can continue execution from now on. Thus, map function works.</li><li>The same steps occur for the 3rd iteration as i explained earlier.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHurRkuXHUcu5RTQsoYTQg.png" /><figcaption>The same zip() example with extra logs</figcaption></figure><p><strong>Flow Example 18 — combine</strong></p><p>Let’s explain <strong>combine()</strong> operator and we hopefully understand the difference from <strong>zip()</strong> operator.</p><p>Let’s explain the below example. The only difference from the previous <strong>zip()</strong> function example is the use of <strong>combine()</strong> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8tMklIBN0UYdwpvKai9nQ.png" /><figcaption>combine() example</figcaption></figure><p>In this example, 1st flow emits value, then 2nd flow delays 4 second. 1st flow does not need to wait the finish of 2nd flow’s delay. 1st flow can freely can continue execution. So 1st flow makes 2 more emissions. As you see, while 2nd flow is in delay, 1st flow can continue execution and makes 3 emissions. When 2nd flow’s delay finished, combine operator care about the last value emitted by two flow, <strong>3 </strong>and<strong> one</strong> is printed. When 2nd flow emits again, <strong>3 </strong>and<strong> two</strong> is printed.When 2nd flow emits again, <strong>3 </strong>and<strong> three</strong> is printed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ErURJbHTN8tYngRikFlA5w.png" /><figcaption>combine() example with more logs</figcaption></figure><p><strong>Another combine example</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1n81l4--JsY85tPOsQaQg.png" /></figure><p>As you see in this example, combine works as the following:</p><ul><li>When one flow makes an emission, if the other flow made an emission before, the last value emitted by each flow is combined and collected for each emission.</li></ul><h3>Flattening flows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*2w-enkb4JYBD_uGxXirMNA.png" /></figure><p>In this example, we have a flow of three integers and called requestFlow23 function for emission of three integers.</p><blockquote>Then we end up with a flow of flows (<em>Flow&lt;Flow&lt;String&gt;&gt;</em>) that needs to be <em>flattened</em> into a single flow for further processing. Collections and sequences have <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/flatten.html">flatten</a> and <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/flat-map.html">flatMap</a> operators for this. However, due to the asynchronous nature of flows they call for different <em>modes</em> of flattening, as such, there is a family of flattening operators on flows.</blockquote><p><strong>Flow Example 19 — Flattening flows using <em>flatMapConcat</em></strong></p><p>Outer flow waits for the inner flow to complete before starting to collect the next one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iftXeQfw_IjrRmiVXcpVHA.png" /></figure><ul><li>In outer flow, 100ms delay occurs, then value <strong>1</strong> is emitted. Inside flatMapConcat, we called requestFlow23() method, and 5 second delay occurs inside inner flow. Outer flow waits for the inner flow to complete for 5 second, then inner flow emits “<strong>1: Second</strong>” and completes.</li><li>In outer flow, 100ms delay occurs, then value <strong>2</strong> is emitted. In inner flow, “<strong>2: First</strong>” is emitted thus collect is invoked, then 5 second delay occurs, then emits “<strong>2: Second</strong>” thus collect is invoked, and completes.</li><li>In outer flow, 100ms delay occurs, then value <strong>3</strong> is emitted. In inner flow, “<strong>3: First</strong>” is emitted thus collect is invoked, then 5 second delay occurs, then emits “<strong>3: Second</strong>” thus collect is invoked, and completes.</li></ul><p>As you see if you use <strong>flatMapConcat</strong>, Outer flow waits for the inner flow to complete before starting to emitting the next value.</p><p><strong>Flow Example 20 — Flattening flows using flatMapMerge</strong></p><blockquote>Another flattening mode is to concurrently collect all the incoming flows and merge their values into a single flow so that values are emitted as soon as possible.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6s8HKXWHzCzWSkdHwR1Dg.png" /><figcaption>flatMapMerge() example</figcaption></figure><ul><li>value <strong>1</strong> is emitted, and inner flow for value <strong>1</strong> delays 5 second.</li><li>Outer flow does not wait inner flow complete its work for value <strong>1</strong>. Thus outer flow emits value <strong>2 and 3.</strong></li><li>When the inner flow completes after 5 second delay, inner flow works for value <strong>2 </strong>and <strong>3</strong>(first in first out order).</li></ul><p>As you see if you use <strong>flatMapMerge()</strong>, outer flow does not wait for the inner flow to complete before starting to emitting the next value. In other words, outer flow and inner flows run concurrently. Collect catches the emissions.</p><p><strong>Note :</strong></p><blockquote>flatMapMerge() accepts an optional <em>concurrency</em> parameter that limits the number of concurrent flows that are collected at the same time (it is equal to <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-d-e-f-a-u-l-t_-c-o-n-c-u-r-r-e-n-c-y.html">DEFAULT_CONCURRENCY</a>(16) by default).</blockquote><blockquote>Note that the <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flat-map-merge.html">flatMapMerge</a> calls its block of code (<em>{ requestFlow(it) }</em> in this example) sequentially, but collects the resulting flows concurrently, it is the equivalent of performing a sequential <em>map { requestFlow(it) }</em> first and then calling <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flatten-merge.html">flattenMerge</a> on the result.</blockquote><p><strong>Flow Example 21 — Flattening flows using flatMapLatest</strong></p><p><strong>flatMapLatest()</strong> has a similar behaviour with collectLatest() which we saw earlier. When you see xxxLatest operator, remember that previous flows are cancelled when new flow is emitted. By using flatMapLatest() operator, when outer flow emits a new value, if there is a flow in progress they all are cancelled. Only the latest emitted value is processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g180lD0Eej6hslQBB-jjtA.png" /><figcaption>flatMapLatest() example</figcaption></figure><p>In this example, since outer flow does not wait the completion of inner flow. Value 1 is emitted and is in progress in inner flow.</p><ul><li>Then value 2 is emitted, thus process of previous emission of value 1 is cancelled.</li><li>Then value 3 is emitted, thus process of previous emission of value 2 is cancelled. Only the emission with value 3 is completed inside inner flow.</li></ul><p>To sum up, difference of the 3 Flattening flow operators is as the following :</p><p><strong>flatMapConcat : </strong>Outer flow waits for the inner flow to complete before starting to collect the next one. Each emission of outer flow processed.</p><p><strong>flatMapMerge :</strong> outer flow does not wait for the inner flow to complete before starting to emit the next value. Each emission of outer flow processed.</p><p><strong>flatMapLatest</strong> <strong>:</strong> outer flow does not wait for the inner flow to complete before starting to emit the next value. At each emission, the processing of old emissions are cancelled. Only the last emission continues execution.</p><p><strong>Flow Exceptions</strong></p><p>Flow emitter, collector, or code inside the flow operators can throw exception. There are several ways to catch and handle the exceptions.</p><p><strong>Flow Example 22 — Handling Exceptions — Strategy 1 — wrap your entire code inside try catch block.</strong></p><p>We can write flow builder and collector directly inside try catch, as in the following. If any exception is thrown inside collector, flow builder, or flow operators, we can catch all of them using this strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WU05DWzRz5Sm34-dzhL71A.png" /></figure><p>In the above example,</p><ul><li>Flow builder emits value <strong>1</strong>. Collector collected the value<strong> 1</strong> and printed it. Then the value is checked. Since value≤1 is true, everything is OK, no exception is thrown, flow continue its work.</li><li>Flow emits value <strong>2</strong>. Collector collected the value<strong> 2</strong> and printed it. Then the value is checked. Since value≤1 is false, exception is thrown. Catch block catches the exception. Flow stops its execution, so no more value is emitted. The string value inside check block is printed when we print throwable inside catch method.</li></ul><p>Using the same exception handling strategy, we can catch exceptions thrown inside flow emitter, as we said earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-n8x0Fn3SGgNnq5O8v5nQ.png" /></figure><p><strong>Flow Example 23 — Handling Exceptions — Strategy 2 — catch() operator</strong></p><p>Rather than, wrapping our flow builder and collector in try catch block, we can use <strong>catch operator.</strong></p><blockquote>The emitter can use a <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/catch.html">catch</a> operator that preserves this exception transparency and allows encapsulation of its exception handling. The body of the <em>catch</em> operator can analyze an exception and react to it in different ways depending on which exception was caught:</blockquote><ul><li>Exceptions can be rethrown using throw.</li><li>Exceptions can be turned into emission of values using <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow-collector/emit.html">emit</a> from the body of <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/catch.html">catch</a>.</li><li>Exceptions can be ignored, logged, or processed by some other code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNUD_ql4HMGTTXStdzxsWQ.png" /></figure><p>In this example,</p><ul><li>Flow builder emits value “1”, then the value is checked inside map operator. The value 1 mapped to the value “string 1”. This value is collected by collector and printed.</li><li>Flow builder emits value “2”, then the value is checked inside map operator. check operator throws exception, catch operator catches the exception, and emits a new value “Caught …”. Collector collects the value “Caught …” and printed.</li><li>Since catch operator catches an exception, flow builder stops execution and don’t emit anything from now on.</li></ul><blockquote><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/catch.html">catch</a> operator preserves exception transparency and allows encapsulation of its exception handling.</blockquote><p><strong>Another catch() operator example with wrong usage — catch operator catches only upstream exceptions, catch operator escapes downstream exceptions</strong></p><blockquote>🔥🔥🔥The <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/catch.html">catch</a> intermediate operator, honoring exception transparency, catches only upstream exceptions (that is an exception from all the operators above <em>catch</em>, but not below it). If the block in <em>collect { ... }</em> (placed below <em>catch</em>) throws an exception then it escapes, as in the following example.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlchKLz4XIh3JfbsLAm2dg.png" /></figure><p>🦖 In this example, when flow emits value 2, collector collects it, then check operator throws exception. Catch operator cannot catch the exception because catch operator can catch only upstream exceptions and exception occurred in this example in the downstream of catch operator. In other words, since catch is called before collect(), catch operator cannot catch exceptions occurred in collector.</p><p><strong>Another catch operator example which solves the previous non-catchable exception problem — Catch declaratively</strong></p><blockquote>We can combine the declarative nature of the <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/catch.html">catch</a> operator with a desire to handle all the exceptions, by moving the body of the <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/collect.html">collect</a> operator into <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/on-each.html">onEach</a> and putting it before the <em>catch</em> operator. Collection of this flow must be triggered by a call to <em>collect()</em> without parameters:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTVuqotedcldpsDvsK7jkA.png" /></figure><p>As you see in this example, we moved the collector body to inside of onEach operator. We write onEach operator before catch operator. By using this way, catch operator can catch all exceptions because exception cannot be occur inside collector, and we write all collector codes inside onEach operator.</p><p>When value 2 is emitted, exception is thrown from onEach operator. Catch operator catches the exception. Flow builder stops execution.️ Collector cannot collect the value 2. 👈👈🤹‍♂️️️️️️🤹‍ 🤹‍♂️️️️️️🤹‍</p><p><strong>Flow completion</strong></p><blockquote>When flow collection completes (normally or exceptionally) it may need to execute an action. As you may have already noticed, it can be done in two ways: imperative or declarative.</blockquote><p><strong>Flow Example 24.1 — Imperative finally block example, try catch finally</strong></p><p>In addition to try/ catch, a collector can also use a finally block to execute an action upon collect completion.</p><p>🦖As you guess, after flow completes its job, or after catch operator catches an exception, finally block is invoked.</p><p>In the following example, after flow completes its job, finally block is invoked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*Xa4D-prgdUnhz_sPUobCQg.png" /><figcaption>imperative finally block example 1</figcaption></figure><p>In the following example, after catch block catches an exception, finally block is invoked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*_V0stBaMRELKExO8HoYA3Q.png" /><figcaption>imperative finally block example 2</figcaption></figure><p><strong>Flow example 24.2 — Declarative completion example — onCompletion operator</strong></p><p>In the following example, after flow completes its job, onCompletion operator is invoked. In other words, flow builder emits all its emissions, collector collected all emissions. No exception occurred. Then onCompletion() is invoked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*Jx0FOiBy_Pi4lf8_GjQKEw.png" /></figure><p>In the following example, flow builder emits value 2, then check operator throws an exception. Then catch block catches that exception. Then onCompletion operator is invoked with nonnull parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wVKnMxG3hKYPhiOc6xdkQ.png" /></figure><p>No need to say that you can call onEach operator just after the flow builder as in the below example. The below and above example is the same. Keep that in mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgfHfEv_xHi7OlZweDOl6A.png" /></figure><p>Note that, in these examples, we see only check operator throw exception. However, anything can throw exception, for example an exception can be thrown inside collector, flow builder, or intermediate flow operators, as the following,</p><pre>throw RuntimeException()</pre><p>🔥 Question :</p><p>When onCompletion operator is invoked, how do you understand if the flow completed normally, or an exception occurred ?</p><p>🔥 Answer :</p><p>By checking the parameter of <strong>onCompletion</strong> operator. If it is null, you understand that flow completed normally. If it is not null, an exception occurred, then catch operator is invoked, then onCompletion block is invoked.</p><p><strong>Flow Example 25 — An important difference between onCompletion and onCatch operator</strong></p><p>onCompletion sees all exceptions, whether the exception occurs in the upstream, or downstream. It does not matter. However, as we said earlier, catch operator catches only upstream operator. You can see that from the below example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QKRoeUmt5WjjxaPFCLImw.png" /><figcaption>onCompletion() catches all exceptions. catch() catches only upstream exceptions.</figcaption></figure><p><strong>Flow Example 26 — collect vs launchIn</strong></p><p>You are going very well. We come to the last of the flow article. We learned that collect() is a terminal operator and used many times in our previous examples. However, i have not mentioned about one important thing about collect terminal operator yet. Guess that ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhUGjwdXV5R1bjkmzrtqqQ.png" /></figure><p>Ok ok i’m saying that :</p><p>Collect terminal operator is a suspending function so if your collector or emitter is slow, the next lines of codes are waiting for your collector to finish as in the following and all of our previous examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpW9buOG01_6AJ2N-sIFZQ.png" /><figcaption>Collect terminal operator is a suspending function</figcaption></figure><p>In the above example, in order to run the following</p><pre><em>println</em>(&quot;Done&quot;)</pre><p>we must wait for 30 seconds. Whaaat ! If you have such a situation, and do not want to collector to block the execution of the next line, you can use the <strong>launchIn</strong> terminal operator. Below is a screenshot from its definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zj7N_InB1DG_NnIlD82NJA.png" /><figcaption><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/launch-in.html">https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/launch-in.html</a></figcaption></figure><p>As you see, launchIn works as fire and forget rather than suspending. launchIn() takes CoroutineScope as a parameter.</p><p>The following two examples are the same.</p><p>In the below example which use launchIn(), this scope comes from the <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html">runBlocking</a> coroutine builder. Firstly runBlocking completes, then the coroutine launched inside runBlocking() starts to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Su34nc5p07QyLMHSzvdutQ.png" /></figure><p>Both examples print “Done” firstly because launchIn() is a shorthand for</p><pre>scope.launch{<br>    flow.collect()<br>}</pre><blockquote>Note that <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/launch-in.html">launchIn</a> also returns a <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html">Job</a>, which can be used to <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/cancel.html">cancel</a> the corresponding flow collection coroutine only without cancelling the whole scope or to <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/join.html">join</a> it.</blockquote><p><strong>Flow Example 27 — Cancelling flow emission</strong></p><p>For convenience, the <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flow.html">flow</a> builder</p><pre><em>flow </em><strong>{<br>    ...</strong><br><strong>}</strong></pre><p>performs additional <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/ensure-active.html">ensureActive</a> checks for cancellation on each emitted value.</p><p>In the following example, when value 3 is emitted, we cancel the flow emission. As you see, collector for value 3 continue to work and completed normally. Also flow builder continue normally until it comes to emission. When the flow builder emits, JobCancellationException occurs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PoWq4ZItbXb7469bciSFqQ.png" /></figure><p><strong>Flow Example 28 — Many flow operators don’t do cancellation check for performance reasons</strong></p><p>Checking whether the flow is cancelled comes with a cost . Thus, for performance reasons, many flow operators don’t do cancellation check.</p><blockquote>For example, if you use <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/kotlin.ranges.-int-range/as-flow.html">IntRange.asFlow</a> extension to write the same busy loop and don’t suspend anywhere, then there are no checks for cancellation. All numbers from 1 to 5 are collected and cancellation gets detected only before return from <em>runBlocking,</em> in the following example.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxerVPnzMjZ8WyOPdj5IoQ.png" /><figcaption>asFlow operator is not cancellable by default</figcaption></figure><p><strong>Flow Example 29 — How to do cancellation check when using flow operators which don’t do cancellation check</strong></p><p>Say that you want to use a flow operator(for example, asFlow operator) which doesn’t do cancellation check but you want to do cancellation check. There are 2 different ways to do it.</p><p><strong>1st way:</strong> <strong><em>asFlow()</em></strong><em> doesn’t do cancellation check. Before each emission, checking </em><strong><em>ensureActive()</em></strong><em> makes </em><strong><em>asFlow() </em></strong><em>cancellable.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wyx9-hsJusNyf1cCmwuYLg.png" /><figcaption>Make asFlow operator cancellable manually — way 1</figcaption></figure><p><strong>2nd way : </strong><em>For example,</em><strong><em> asFlow()</em></strong><em> doesn’t do cancellation check. </em><strong><em>asFlow().cancellable()</em></strong><em> makes </em><strong><em>asFlow()</em></strong><em> cancellable.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1oMnoelPkZsr8ccCF1jbA.png" /><figcaption>Make asFlow operator cancellable manually — way 2</figcaption></figure><p>In this article, i used the example and quotations mainly from the following links. I added extra explanatory comments .</p><p><a href="https://kotlinlang.org/docs/flow.html#flow-and-reactive-streams">https://kotlinlang.org/docs/flow.html#flow-and-reactive-streams</a></p><p><a href="https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-core/jvm/test/guide">https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-core/jvm/test/guide</a></p><blockquote>Flow <em>is conceptually </em>a reactive stream. Indeed, its design was inspired by Reactive Streams and its various implementations. But Flow main goal is to have as simple design as possible, be Kotlin and suspension friendly and respect structured concurrency. Achieving this goal would be impossible without reactive pioneers and their tremendous work. You can read the complete story in <a href="https://medium.com/@elizarov/reactive-streams-and-kotlin-flows-bfd12772cda4">Reactive Streams and Kotlin Flows</a> article.</blockquote><p>In my article, i got help from the following links. Check these links for more information.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtYcqn48SMT8%3Fstart%3D383%26feature%3Doembed%26start%3D383&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtYcqn48SMT8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FtYcqn48SMT8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/aea9308ca413faf9472c1f99d3460f36/href">https://medium.com/media/aea9308ca413faf9472c1f99d3460f36/href</a></iframe><ul><li><a href="https://kotlinlang.org/docs/flow.html">Asynchronous Flow | Kotlin</a></li><li><a href="https://elizarov.medium.com/cold-flows-hot-channels-d74769805f9">Cold flows, hot channels</a></li><li><a href="https://www.raywenderlich.com/9799571-kotlin-flow-for-android-getting-started">Kotlin Flow for Android: Getting Started</a></li></ul><p>That’s all for now.</p><p>If you liked, please clap and share.</p><p>Happy flow coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cdb391295b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/digigeek/from-zero-to-hero-series-kotlin-sequences-channels-flows-part-3-flows-5cdb391295b8">From Zero To Hero Series ( Kotlin Sequences, Channels, Flows ) — Part 3 — Flows</a> was originally published in <a href="https://medium.com/digigeek">DigiGeek</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 Kotlin Sequences, Channels, Flows — Part 2— Channels]]></title>
            <link>https://medium.com/digigeek/introduction-to-kotlin-sequences-channels-flows-part-2-channels-c21a7bf8b1cc?source=rss-830264dd5efb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c21a7bf8b1cc</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[ömer iyiöz]]></dc:creator>
            <pubDate>Sun, 27 Jun 2021 18:28:03 GMT</pubDate>
            <atom:updated>2021-07-09T05:16:00.600Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/digigeek/from-zero-to-hero-series-kotlin-sequences-channels-flows-part-1-sequences-3dbba97f55c2?source=your_stories_page-------------------------------------">From Zero To Hero Series</a> ( Kotlin Sequences, Channels, Flows ) — Part 2— Channels</h3><p><strong>Flows are <em>cold</em> streams, Channels are hot streams.</strong></p><p><strong>Flows</strong> are <em>cold</em> streams similar to sequences — the code inside a <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flow.html">flow</a> builder does not run until the flow is collected(until a terminal operator such as collect() function is called).</p><p><strong>Flow</strong> can be used in a fully-reactive programming style. If you&#39;ve used something like RxJava before, Flow provides similar functionality.</p><p>In <strong>channel</strong>, emittor emits items at its own pace, even if there is no collector.</p><p><strong>Shared mutable state</strong></p><p>Writing code with a shared mutable state is known to be quite difficult and error-prone. Sharing information by communication instead of sharing information using the common mutable state tries to simplify this. Coroutines can communicate with each other via <em>channels</em>.</p><p><strong>Channels</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSOT7Eu2MtQsY8m6yH8bEQ.png" /><figcaption><a href="https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/08_Channels">https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/08_Channels</a></figcaption></figure><p>There are 4 types of channels :</p><ul><li>Channel.RENDEZVOUS</li><li>Channel.BUFFERED</li><li>Channel.UNLIMITED</li><li>Channel.CONFLATED</li></ul><p>When you create a channel, you specify its type or the buffer size (if you need a buffered one) :</p><pre>val rendezvousChannel = Channel&lt;String&gt;()<br>val bufferedChannel = Channel&lt;String&gt;(10)<br>val conflatedChannel = Channel&lt;String&gt;(CONFLATED)<br>val unlimitedChannel = Channel&lt;String&gt;(UNLIMITED)</pre><p>The default channel type is <strong>Rendezvous</strong>. If you don’t specify the channel type explicitly, the channel type is Rendezvous.</p><p>Channels are like a <strong>pipe</strong>. You can send information in to one end and receive information from the other end.</p><blockquote>A <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-channel/index.html">Channel</a> is conceptually very similar to <em>BlockingQueue</em>. One key difference is that instead of a blocking <em>put</em> operation it has a suspending <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-send-channel/send.html">send</a>, and instead of a blocking <em>take</em>operation it has a suspending <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-receive-channel/receive.html">receive</a>.</blockquote><p>Thus you can think a channel as a <strong>nonblocking queue</strong>.</p><p>Channels have 2 methods:</p><ul><li>send()</li><li>receive()</li></ul><p>Both send() and receive() methods are suspending methods. These methods can be called only inside coroutines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5fyqOF-yJHH4Y8ulfA3EAg.png" /></figure><p>There are 3 interfaces:</p><ul><li><strong>Channel</strong> (extends both SendChannel and ReceiveChannel)</li><li><strong>SendChannel</strong></li><li><strong>ReceiveChannel</strong></li></ul><p>If you have a Channel object you can both send and receive data. If you have a SendChannel object you can only send data via this channel. If you have a ReceiveChannel object you can only receive data via this channel.</p><p><strong>Rendezvous Channels</strong></p><p>Here is the meaning of rendezvous i take from merriam-webster:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*SbZ4uawEhLPowXDHEO0fyg.png" /></figure><p>A rendezvous channel has no buffer.</p><p><strong>The sending coroutine suspends until a receiver coroutine invokes <em>receive</em> on the channel. Similarly, a consuming coroutine suspends until a producer coroutine invokes <em>send</em> on the channel</strong>. We create a rendezvous channel using the default <em>Channel</em> constructor with no arguments.</p><blockquote>The “Rendezvous” channel is a channel without a buffer; it’s the same as creating a buffered channel with zero size. One of the functions (<em>send</em> or <em>receive</em>) always gets suspended until the other is called. If the <em>send</em> function is called and there&#39;s no suspended <em>receive</em> call ready to process the element, then <em>send</em> suspends. Similarly, if the <em>receive</em> function is called and the channel is empty - or in other words, there&#39;s no suspended <em>send</em> call ready to send the element - the <em>receive</em> call suspends. The &quot;rendezvous&quot; name (&quot;a meeting at an agreed time and place&quot;) refers to the fact that <em>send</em> and <em>receive</em> should &quot;meet on time&quot;.</blockquote><p><strong>Rendezvous Channel example 1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBmJFneyV5cPKi1Sgx4jAA.png" /></figure><p>In this example, we have 2 sender coroutines and 1 receiver coroutine. I explained how this code works.</p><ul><li>1st coroutine tries to send “A1” to channel by calling channel.send(“A1”). send() method suspends the coroutine since there is no receiver coroutine yet.</li><li>2nd coroutine tries to send “B1” to channel by calling channel.send(“B1”). send() method suspends the coroutine since there is no receiver coroutine yet.</li><li>3rd coroutine tries to receive values from channel if any sender coroutine waits. 1st coroutine and 3rd coroutine meets, 1st coroutine sends the value to channel and 3rd coroutine takes the value from channel. 1st coroutine is no longer suspending and waits its turn for working.</li><li>3rd coroutine continue to work and meets with 2nd coroutine. Thus, 2nd coroutine sends the value to channel and 3rd coroutine takes the value from channel. 2nd coroutine is no longer suspending and waits its turn for working.</li><li>3rd coroutine continue to work. However, this time, when channel.receive() is called, no coroutine waits for sending some value to channel, there is no suspending send() method exists. Thus channel.receive() suspends 3rd coroutine.</li><li>Now it’s 1st coroutine’s turn. channel.send(“A2”) is called but not suspends since receiver(3rd) coroutine waits for receiving. Since it’s 1st coroutine’s turn, 1st coroutine continues to work, and finishes. 3rd coroutine now is not suspending but waits for its turn.</li><li>Now it’s 2nd coroutine’s turn. Only something is printed.</li><li>Then it’s 3rd coroutine’s turn. channel.receive takes the “A2” from channel and ends.</li></ul><p><strong>Rendezvous Channel example 2</strong></p><p>If you call send() and receive() in the same Coroutine, this coroutine never terminates. If you understand the channels correctly, doing this already illogical because the purpose of channels is sending values between different coroutines.</p><pre>// The following coroutine never terminates.<br>val channel1 = Channel&lt;String&gt;()<br>launch {<br>    channel1.send(&quot;value&quot;)<br>    channel1.receive()<br>}</pre><pre><em>// The following coroutine never terminates.<br></em>val channel1 = Channel&lt;String&gt;()<br>launch {<br>    channel2.send(&quot;value&quot;)<br>    channel2.receive()<br>}</pre><p><strong>Rendezvous Channel example 3</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J84wHyNKA9zas5rI0dMbTg.png" /></figure><ul><li><em>Coroutine2</em> tries to send the value <strong>1</strong> and immediately suspends it as there are no receivers.</li><li>receive() is called in <em>Coroutine1, thus Coroutine1 </em>receives the value <strong>1, </strong>and<strong> </strong><em>Coroutine2</em> now un-suspends but waits its turn to work.</li><li>Then<strong> </strong>receive() is called again but this time receive() suspends the <em>Coroutine1</em> as there is no more values to be received from the channel.</li><li><em>Then it’s coroutine2’s turn to work. Thus coroutine2 works </em>and sends the value 2 to the channel, since a receiver waits at the other end of the channel. Coroutine1 un-suspends but waits its turn to work.</li><li>Coroutine2 continue to iterate and try to send <strong>3</strong> immediately suspends it as there are no receivers. And so on..</li></ul><p><strong>Rendezvous Channel example 4 — Closing the channel on sender coroutine, and, receiving data from channel using for loop in receiver coroutine</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y16ns3YDpnEHT3USkQJmig.png" /></figure><p>In receiver coroutine, rather than iterating 5 times using repeat(5) and calling channel.receive(), we can iterate on channel using for loop and we can access the received data directly without need to call channel.receive().</p><blockquote>Closing a channel conceptually works by sending a special “close token” over this channel. You close a channel when you have a finite sequence of elements to be processed by consumers and you must signal to the consumers that this sequence is over. You don’t have to close a channel otherwise.</blockquote><blockquote>Channels are not tied to any native resource and they don’t have to be closed to release their memory. Simply dropping all the references to a channel is fine. GC will come to do clean it up.</blockquote><p><strong>Channel example 5 — coroutine builder function produce(), and, consumeEach extension function</strong></p><p>We can update the above examples by using Channel idiomatic keywords, <strong><em>produce()</em></strong><em> </em>and<em> </em><strong><em>consumeEach()</em></strong>.</p><blockquote>The produce() extension-function is a beauty. What it does is, it creates a new Channel for us and returns it as a ReceiverChannel, which encapsulates the sending functionality within the produce-function. Outside of the closure, we can only receive from the Channel. The produce-function automatically closes the Channel when the closure is done. So you won’t accidentally end up with a coroutine and Channel that never terminates.</blockquote><blockquote>Launches a new coroutine to produce a stream of values by sending them to a channel and returns a reference to the coroutine as a <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-receive-channel/index.html">ReceiveChannel</a>. This resulting object can be used to <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-receive-channel/receive.html">receive</a> elements produced by this coroutine.</blockquote><p><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/consume-each.html">consumeEach</a> is an extension function, which replaces a for loop on the consumer side. <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/consume-each.html">consumeEach</a> will become obsolete in future so you shouldn’t use it.</p><pre>fun CoroutineScope.produceSquares(): ReceiveChannel&lt;Int&gt; = <em>produce </em><strong>{<br>    </strong>for (x in 1..5) send(x * x)<br><strong>}</strong></pre><pre>fun main() = <em>runBlocking </em><strong>{</strong></pre><pre><strong>    </strong><em>// 1st way of sending integers to the channel.<br>    /*val squares = Channel&lt;Int&gt;()<br>    launch {<br>        for (x in 1..5)<br>            squares.send(x * x)<br>        squares.close() // we&#39;re done sending<br>    }*/<br>    // 2nd way of sending integers to the channel.<br>    </em>val squares = <em>produceSquares</em>()<br></pre><pre>    <em>// 1st way of receiving integers from the channel.<br>    </em>squares.consumeEach <strong>{<br>        </strong>delay(3000)<br>        <em>println</em>(<strong>it</strong>)<br>    <strong>}<br>    </strong><em>// 2nd way of receiving integers from the channel.<br>    /*repeat(5) {<br>        delay(3000)<br>        println(squares.receive())<br>    }*/</em></pre><pre><em>    println</em>(&quot;Done!&quot;)<br><strong>}</strong></pre><p>In the above example, i showed the two different ways for producing and consuming integers in channel. 1st way and 2nd way is equivalent and does the same job, so you can choose one of these 2 ways.</p><p><strong>Output :</strong></p><pre>(3 second delay)<br>1<br>(3 second delay)<br>4<br>(3 second delay)<br>9<br>(3 second delay)<br>16<br>(3 second delay)<br>25<br>Done!</pre><p>In my article, i got help from the following links. Check these links for more information.</p><ul><li><a href="https://www.baeldung.com/kotlin/channels">Introduction to Channels in Kotlin | Baeldung on Kotlin</a></li><li><a href="https://medium.com/analytics-vidhya/channels-in-kotlin-part-two-7d52abbc5b6e">Channels in Kotlin — part two</a></li><li><a href="https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/08_Channels">Kotlin Playground: Edit, Run, Share Kotlin Code Online</a></li></ul><p>That’s all for now.</p><p>See you in the 3rd part of this article for Flows.</p><p>Happy Channel Coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c21a7bf8b1cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/digigeek/introduction-to-kotlin-sequences-channels-flows-part-2-channels-c21a7bf8b1cc">Introduction to Kotlin Sequences, Channels, Flows — Part 2— Channels</a> was originally published in <a href="https://medium.com/digigeek">DigiGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero To Hero Series — Kotlin Sequences, Channels, Flows — Part 1 — Sequences]]></title>
            <link>https://medium.com/digigeek/from-zero-to-hero-series-kotlin-sequences-channels-flows-part-1-sequences-3dbba97f55c2?source=rss-830264dd5efb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dbba97f55c2</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[ömer iyiöz]]></dc:creator>
            <pubDate>Sat, 17 Apr 2021 22:02:00 GMT</pubDate>
            <atom:updated>2021-06-28T15:56:04.524Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/digigeek/from-zero-to-hero-series-kotlin-sequences-channels-flows-part-1-sequences-3dbba97f55c2?source=your_stories_page-------------------------------------">From Zero To Hero Series</a>(Kotlin Sequences, Channels, Flows) — Part 1— Sequences</h3><p>Kotlin language constains a container type which is called <strong>sequences</strong>. Sequences are very similar to lists. The difference between a list and sequence is that the sequences are <strong>lazily evaluated</strong>.</p><p>We can create sequences with different ways:</p><p><strong>1 — From elements — </strong>By calling <strong>sequenceOf()</strong></p><pre><strong>val </strong>numbersSequence = sequenceOf(<strong>&quot;four&quot;</strong>, <strong>&quot;three&quot;</strong>, <strong>&quot;two&quot;</strong>, <strong>&quot;one&quot;</strong>)</pre><p>We give elements as parameter to <strong>sequenceOf() </strong>function.</p><p><strong>2- From iterable objects</strong> — By calling <strong>asSequence()</strong> function of an iterable object such as a List or Set.</p><pre><strong>val </strong><em>numbers </em>= <em>listOf</em>(<strong>&quot;one&quot;</strong>, <strong>&quot;two&quot;</strong>, <strong>&quot;three&quot;</strong>, <strong>&quot;four&quot;</strong>)<br><strong>val </strong><em>numbersSequence </em>= <em>numbers</em>.<em>asSequence</em>()</pre><p>We can create a sequence by calling <strong>asSequence()</strong> function of an iterable object such as a List or Set.</p><p><strong>3-From Chunks </strong>— <strong><em>sequence </em>{}, yield, yieldAll()</strong></p><pre><strong>val </strong><em>seqFromChunks </em>= <em>sequence </em><strong>{<br>    </strong>yield(1)<br>    yieldAll((2..5).<em>toList</em>())<br>    yield(6)<br><strong>}</strong></pre><p>Sequences execute lazily.</p><ul><li>What does it mean ? Can you show me with an example ?</li><li>Yeap. I will show you it in example 1.</li></ul><p><strong>Sequence Example 1 :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hiMWQD-45KhTETg45wpqRg.png" /><figcaption>Compare the two examples above. First example is not using sequences. Second example is using sequences.</figcaption></figure><p><strong>Sequence Example 2 :</strong></p><p>In this example, we use sequence{} to create a sequence. When we call</p><pre>sequence.take(5).toList()</pre><p>the codes inside the sequence{} start to work. When 5 elements are taken into sequence, the execution stops. Thus the next lines of codes are not executed. Analyse the following examples to understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sfc_3Lfq0ktImI8tWsmhIQ.png" /><figcaption>These two examples shows creating sequence from chunks. Lazy evaluation works here too.</figcaption></figure><p>Note that,</p><ul><li>sequences are not asynchoronous.</li><li>sequences don’t support backpressure.</li></ul><p><strong>Benchmark Results between Sequences, RxJava and Flows</strong></p><p>According to a benchmark results on scrabble game, Kotlin Flows are nearly 2 times faster than RxJava. Flows are a bit slower than Sequences. However Flows give you more possibilities, you can have asynchronous data producers, it supports backpressure. Since Flows support backpressure, it comes with a little overhead thus it’s a bit slower than sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdMZgP9yZulJ100ll5-FBw.png" /><figcaption>KotlinConf 2019: Asynchronous Data Streams with Kotlin Flow by Roman Elizarov</figcaption></figure><p><strong>Difference between Sequence and Flow</strong></p><p>Flows are asynchronous data stream.</p><blockquote><em>A flow is an asynchronous version of a </em><a href="https://kotlinlang.org/docs/reference/sequences.html"><em>Sequence</em></a><em>, a type of collection whose values are lazily produced. Just like a sequence, a flow produces each value on-demand whenever the value is needed, and flows can contain an infinite number of values.</em></blockquote><p>In my article, i got help from the following links. Check these links for more information.</p><ul><li><a href="https://en.proft.me/2018/12/20/lazy-sequences-kotlin/">Lazy sequences in Kotlin | en.proft.me</a></li><li><a href="https://kotlinlang.org/docs/sequences.html#sequence-processing-example">Sequences | Kotlin</a></li></ul><p>That’s all for now. See you in the 2nd part of this article for Channels.</p><p>Happy Sequence Coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dbba97f55c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/digigeek/from-zero-to-hero-series-kotlin-sequences-channels-flows-part-1-sequences-3dbba97f55c2">From Zero To Hero Series — Kotlin Sequences, Channels, Flows — Part 1 — Sequences</a> was originally published in <a href="https://medium.com/digigeek">DigiGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ktlint kullanımı— Android]]></title>
            <link>https://medium.com/digigeek/ktlint-kullan%C4%B1m%C4%B1-android-3d09f40d22a8?source=rss-830264dd5efb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d09f40d22a8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ktlint]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[linter]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[ömer iyiöz]]></dc:creator>
            <pubDate>Mon, 29 Mar 2021 05:14:47 GMT</pubDate>
            <atom:updated>2021-04-01T07:33:15.520Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba değerli Android geliştiriciler ,</p><p>bu yazımda ktlint’den bahsedeceğim. KtLint kullanarak kotlin projenizde kotlin style guide’larına uyup uymadığını kontrol edebilirsiniz. Style guideline’a uygun şekilde projenizin tamamının otomatik olarak formatlanmasını sağlayabilirsiniz. Ayrıca Command Shift L kısa yolu ile yaptığınız auto indentation’ı ktlint format’lamaya bağlayabilirsiniz.</p><p>Hızlıca başlayalım.</p><p>Projenize KtLint’i entegre etmenin farklı yolları var. Temel olarak ise plugin’li ve pluginsiz entegre etmek olarak 2 farklı yolu var diyebiliriz. Bu yazımda</p><p><a href="https://github.com/jlleitschuh/ktlint-gradle">https://github.com/jlleitschuh/ktlint-gradle</a> adresindeki plugin’i entegre edeceğim, ancak diğer yollardan da bahsedeceğim.</p><p><strong>1- ktlint plugin eklenmesi</strong></p><p>root level build.gradle’ınıza aşağıda plugin’i eklemelisiniz.</p><pre><em>// root-level build.gradle<br></em>plugins <strong>{<br>    </strong>id &quot;org.jlleitschuh.gradle.ktlint&quot; version &quot;10.0.0&quot;<br><strong>}</strong></pre><p><strong>2- ktlint plugin’in apply edilmesi</strong></p><p>root level build.gradle’ınıza aşağıdaki kodu eklemelisiniz. Bu plugin mavenCentral içerisinden geldiği için mavenCentral da eklenmelidir.</p><pre>allprojects <strong>{<br>    </strong>repositories <strong>{<br>        //blah blah</strong><br>        mavenCentral()<br>    <strong>}<br>    </strong>apply plugin: &quot;org.jlleitschuh.gradle.ktlint&quot;<br><strong>}</strong></pre><p>Entegrasyon okdir booom! Ktlint’i bilgisayarımıza kurmaya bile gerek kalmadı fark ettiyseniz. Normalde bilgisayarımıza Ktlint’i kurarak çalıştırabileceğimiz komut satırlarını çalıştırabilmek için</p><p><strong>3— Kodu ktlint’e göre check etmek</strong></p><p>Projemizi ktlint’e göre check etmek için Android studio’da terminal içerisinde aşağıdaki kodu çalıştıralım</p><pre>./gradlew ktlintCheck</pre><p>Eğer bir problem varsa detayını görmek için bu komutun sonuna</p><pre>--stacktrace</pre><p>ekleyerek çalıştırabilirsiniz :</p><pre>./gradlew ktlintFormat --stacktrace</pre><p><strong>4 — Kodu ktlint’e göre formatlamak</strong></p><p>Projemizin ktlint’e uygun şekilde otomatik olarak formatlanması için aşağıdaki kodu çalıştıralım</p><pre>./gradlew ktlintFormat</pre><p>5 — 🔥 <strong>ktlint’i tüm Android Projelerimde kullanmak istiyorum diyenler, oto format olarak ktlint formatlama kullanmak istiyorum diyenlerrr buraya</strong> 🔥</p><p>Yukarıdaki kodu çalıştırdıktan sonra otomatik olarak formatlanmış bir kotlin kodunu açalım. Bu kodda Command Shift L diyerek oto format yaptığımızda farklı bir şekilde formatlama yapılır. Üzerinde çalıştığımız android projemizde oto formatlamanın ktlint formatına göre yapılmasını istiyorsak şu komutu vermeliyiz</p><pre>./gradlew ktlintApplyToIdea</pre><p>Bu komut .idea klasörü altındaki dosyalarda değişiklik yapar. Dolayısıyla .idea klasörünü silerseniz bu komutu tekrar çalıştırmanız gerekir.</p><p>🐎 🐎 🐎 Eğer tüm android studio projelerinizde ktlint style’ı kullanılsın istiyorsanız aşağıdaki komutu bir kereye mahsus çağırabilirsiniz.</p><pre>ktlint applyToIDEAProject</pre><p>Bu komutu çalıştırdıktan sonra ktlint entegrsayonunu yapmadığınız herhangi bir projede bile aşağıdaki komutu çalıştırarak ktlint’e göre formatlama yapabilirsiniz.</p><pre>ktlint -F</pre><p>ktlint check yapmak için ise</p><pre>ktlint</pre><p>komutunu çalıştırabilirsiniz. <strong>ktlint</strong> ile başlayan komutların çalışabilmesi için bilgisarınıza ktlint kurmalısınız. brew install ktlint diyerek kurulum yapabilirsiniz.</p><p><strong>6 — installGitPreCommitHook</strong></p><p>Commit’lemeden önce kodunuzu ktlint ile check etmeyi unutmak istemiyorsanız, ktlint’in bunun için de bir çözümü var.</p><p>Ktlint’i bilgisayarınıza kurduysanız, aşağıdaki komutu çalıştırabilirsiniz.</p><pre>ktlint installGitPreCommitHook</pre><p>Ktlint’i bilgisayarınıza kurmadıysanız ve aşağıdaki plugin’i kullanıyosanız, github readme içerisinde preCommitHook diye aratarak size lazım olan komutu bulabilirsiniz.</p><p><a href="https://github.com/jlleitschuh/ktlint-gradle">https://github.com/jlleitschuh/ktlint-gradle</a></p><pre>./gradlew addKtlintCheckGitPreCommitHook<br>./gradlew addKtlintFormatGitPreCommitHook</pre><p>Böylece kodunuzu commit’lemek istediğinizde kodunuz siz unutsanız bile ktlint’e göre check edilir. Eğer sorun varsa kodunuz commit edilemez, ktlint size sorunlu yerleri gösterir.</p><p><strong>7 — Suppress ktlint check</strong></p><p>Kodunuzun bir yerinin ktlint’e göre check edilmemesini istiyorsanız, o kısıma aşağıdaki sihirli satırları ekleyebiliriz.</p><pre><em>// ktlint-disable</em></pre><pre><em>/* ktlint-disable */</em><br>...<br><em>/* ktlint-disable */</em></pre><p><strong>Plugin’siz KtLint kullanmak</strong></p><p>Burda şu mantığı anlamak önemlidir. Ktlint için bir plugin’i projemize eklediğimizde bu plugin bize kullanabileceğimiz hazır gradle task implementation’larını verir. Ancak biz plugin kullanmazsak gerekli olan gradle task’larını kendimiz manual olarak yazmak zorunda kalırız.</p><p>Tavsiye edilen yol bu değil ancak kullanmak istiyorsak veya farklı projelerde görürsek ne olduğunu bilelim diye açıklıyorum. Kodları şurdan aldım <a href="https://github.com/pinterest/ktlint">https://github.com/pinterest/ktlint</a></p><p>Bu kodları root level build.gradle’a değil app level build.gradle’a kopyalayalım.</p><pre>repositories <strong>{<br>    </strong>mavenCentral()<br><strong>}<br><br></strong>configurations <strong>{<br>    </strong>ktlint<br><strong>}<br><br></strong>dependencies <strong>{<br>    </strong>ktlint &quot;com.pinterest:ktlint:0.41.0&quot;<br>    <em>// additional 3rd party ruleset(s) can be specified here<br>    // just add them to the classpath (e.g. ktlint &#39;groupId:artifactId:version&#39;) and<br>    // ktlint will pick them up<br></em><strong>}<br><br></strong>task ktlint(type: JavaExec, group: &quot;verification&quot;) <strong>{<br>    </strong>description = &quot;Check Kotlin code style.&quot;<br>    classpath = configurations.ktlint<br>    main = &quot;com.pinterest.ktlint.Main&quot;<br>    args &quot;src/**/*.kt&quot;<br>    <em>// to generate report in checkstyle format prepend following args:<br>    // &quot;--reporter=plain&quot;, &quot;--reporter=checkstyle,output=${buildDir}/ktlint.xml&quot;<br>    // to add a baseline to check against prepend following args:<br>    // &quot;--baseline=ktlint-baseline.xml&quot;<br>    // see https://github.com/pinterest/ktlint#usage for more<br></em><strong>}<br></strong>check.dependsOn ktlint<br><br>task ktlintFormat(type: JavaExec, group: &quot;formatting&quot;) <strong>{<br>    </strong>description = &quot;Fix Kotlin code style deviations.&quot;<br>    classpath = configurations.ktlint<br>    main = &quot;com.pinterest.ktlint.Main&quot;<br>    args &quot;-F&quot;, &quot;src/**/*.kt&quot;<br><strong>}</strong></pre><p>Fark ettiyseniz, plugin’li örnekte çağırdığımız ktlintCheck ve ktlintFormat task’larının definition’larını kodumuzun içine kendimiz yazdık burda. Aşağıdaki iki komutu komut satırında çalıştırarak yukarıdaki gradle task’larını çağırabiliriz, bu şekilde de ktlint ile çalışabiliriz.</p><pre>./gradlew ktlintFormat<br>./gradlew ktlint</pre><p>Çalıştırabileceğiniz komutları görmek için, aşağıdaki komutu çalıştırabilirsiniz :</p><pre>./gradlew ktlint --help</pre><p>Bilgisayarınız ktlint’i kurduysanız, aşağıdaki komutu çağırarak da aynı sonucu alabilirsiniz.</p><pre>ktlint --help</pre><p><strong>KtLint kurulumu</strong></p><p>Daha önce bahsettiğim üzere, plugin kullanıyorsanız, KtLint’i bilgisayarınıza kurmaya gerek yok, ancak bazı durumlarda ihtiyacınız olabilir, örneğin ktlint’i tüm android projelerinizde kullanmak için applyToIDEAProject komutunu çalıştırdıktan sonra ktlint’i entegre etmediğiniz projeyi ktlint’e göre check etmek formatlamak mümkün, bunun için ise aşağıdaki komutla ktlint’i kurabilirsiniz.</p><pre>brew install ktlint</pre><p>Not : Komutlar arasında kayboluyorsanız, oh my sh ‘ı terminal’inize yüklemenizi tavsiye ederim, Ctrl R yaparak geçmiş tüm komutlarınızı görüp istediğiniz komutu çalıştırabilirsiniz, auto suggestion özelliğinden faydalanabilirsiniz.</p><p>Faydalı olabileceğini düşündüğüm kaynaklar :</p><ul><li><a href="https://github.com/pinterest/ktlint">GitHub - pinterest/ktlint: An anti-bikeshedding Kotlin linter with built-in formatter</a></li><li><a href="https://www.rockandnull.com/static-code-analysis-android/">Static code analysis tools for Android (Kotlin)</a></li><li><a href="https://github.com/jlleitschuh/ktlint-gradle">GitHub - JLLeitschuh/ktlint-gradle: A ktlint gradle plugin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d09f40d22a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/digigeek/ktlint-kullan%C4%B1m%C4%B1-android-3d09f40d22a8">Ktlint kullanımı— Android</a> was originally published in <a href="https://medium.com/digigeek">DigiGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn MotionLayout step by step — Part 2 : <ConstraintSet>,<Constaint>, <OnClick>, clickAction]]></title>
            <link>https://medium.com/digigeek/learn-motionlayout-step-by-step-part-2-constraintset-constaint-onclick-clickaction-bb8570a05bfa?source=rss-830264dd5efb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb8570a05bfa</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[motionlayout]]></category>
            <dc:creator><![CDATA[ömer iyiöz]]></dc:creator>
            <pubDate>Thu, 04 Mar 2021 11:46:31 GMT</pubDate>
            <atom:updated>2021-04-01T07:32:59.756Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn MotionLayout step by step — Part 2 : &lt;ConstraintSet&gt;,&lt;Constaint&gt;, &lt;OnClick&gt;, clickAction</h3><p>At the end this article, you will understand the use of the following in scene file :</p><ul><li>&lt;ConstraintSet&gt; and &lt;Constaint&gt;</li><li>&lt;OnClick&gt; inside &lt;Transition&gt;.</li><li>clickAction attribute of &lt;OnClick&gt;</li></ul><p><strong>Example 3 :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*EMnJlBJS_mCmAGz284l5NA.gif" /><figcaption>When textView is clicked, position of textView changes from top,left to bottom right and vice versa gradually.</figcaption></figure><p>Below is the codes of our 3rd example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0Vy1DdKkB4be6sRSaDv2A.png" /></figure><p>Let me explain the below code, firstly.</p><pre>&lt;OnClick<br>    app:clickAction=&quot;toggle&quot;<br>    app:targetId=&quot;@id/textView3&quot; /&gt;</pre><ul><li>At the <em>first click</em> on <strong>textView3</strong> , the animation plays from <strong>start to end</strong>.</li><li>If we click <strong>textView3</strong> again, the animation plays from <strong>end to start</strong>.</li><li>If we click <strong>textView3</strong> again, the animation plays from <strong>start to end</strong>.</li><li>If we click <strong>textView3</strong> again, the animation plays from <strong>end to start</strong>.</li><li>and so on …</li></ul><p>It’s the result of <strong><em>toggle</em> clickAction</strong>.</p><p>MotionScene file contains two ConstraintSet,</p><ul><li>one for applying at the start of animation,</li><li>one for applying at the end of animation.</li></ul><p>At the <strong>start of animation</strong>, the constraints inside <strong>start constraintSet</strong> is applied. Thus textView3 is at the top left of its parent.</p><p>At the <strong>end of animation</strong>, the constraints inside <strong>end constraintSet</strong> is applied. Thus textView3 is at the bottom right of its parent.</p><p><strong>Example 4 :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*SPABljgp6N8YnIx7fr40PQ.gif" /><figcaption>By swiping, the position of 3 imageViews change gradually.</figcaption></figure><p>Below is the codes of our 4th example :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6k-fsk7XBSuFFa_vnJQ1Gw.png" /></figure><p><strong>OnSwipe</strong></p><pre>&lt;OnSwipe app:touchAnchorId=&quot;@id/imageViewRun&quot; /&gt;</pre><p>swiping starts the animation. While swiping, the anchored view is imageRun, which means <strong><em>imageViewRun</em></strong><em> tracks your finger position. In other words, </em><strong><em>imageViewRun </em></strong><em>moves as you swipe but t</em>he distance between the <strong>imageViewRun</strong> and your swiping finger remains unchanged while swiping.</p><p><strong>touchAnchorId</strong></p><p>When you touch any point inside the MotionLayout screen, and move your finger, <strong><em>imageViewRun</em></strong><em> tracks your finger position</em>. MotionLayout will keep imageViewRun the same distance from the finger that’s swiping.</p><p>For example, when you move your finger -100pixel in y coordinate, then the y coordinate of imageViewRun changes -100pixel.</p><p>I shared the examples in the following github repo. Feel free to contribute.</p><p><a href="https://github.com/oiyio/MotionLayoutSamples.git">oiyio/MotionLayoutSamples</a></p><p>Happy Coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb8570a05bfa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/digigeek/learn-motionlayout-step-by-step-part-2-constraintset-constaint-onclick-clickaction-bb8570a05bfa">Learn MotionLayout step by step — Part 2 : &lt;ConstraintSet&gt;,&lt;Constaint&gt;, &lt;OnClick&gt;, clickAction</a> was originally published in <a href="https://medium.com/digigeek">DigiGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[androidId — Kullanıcılarınız için unique bir string]]></title>
            <link>https://omeriyioz.medium.com/androidid-kullan%C4%B1c%C4%B1lar%C4%B1n%C4%B1z-i%C3%A7in-unique-bir-string-fc530c18bd2e?source=rss-830264dd5efb------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc530c18bd2e</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-apps]]></category>
            <dc:creator><![CDATA[ömer iyiöz]]></dc:creator>
            <pubDate>Tue, 02 Mar 2021 08:41:00 GMT</pubDate>
            <atom:updated>2021-03-02T08:49:48.456Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>androidId — Kullanıcılarınız için unique bir string</strong></p><p>Aşağıdaki kodu kullanarak androidId bulunabilir. Uygulamalarınızda, kullanıcılara özel bir unique bir string’e ihtiyacınız varsa androidId’yi kullanabilirsiniz. androidId, 64-bit bir sayıdır ve hexadecimal string ile gösterilir. Örnek : <strong>44ecc5b239c308ba</strong></p><pre>val androidId = &quot;&quot; + Settings.Secure.getString(context.<em>contentResolver</em>, Settings.Secure.<em>ANDROID_ID</em>)</pre><p>Aynı device’da aynı kullanıcı ile 2 farklı uygulamada çalıştırsanız aynı string’i elde edersiniz.(api26 üzeri ve altı için bu durum aynı keystore ile imzalanmış mı durumuna göre farklılık gösterir. )</p><ul><li>Factory reset atılınca <strong>androidId</strong> değişir.</li><li>Uygulama silip tekrar yükleyince <strong>androidId</strong> değişmez.</li><li>Telefonda 2 farklı user varsa, her iki user’ın da androidId’si farklıdır.</li><li>Root’lanmış cihazlarda androidId değiştirilebilir.</li><li>androidId’nin arasıra null gelebildiği belirtilmiş bazı Stackoverflow yorumlarında, şu an hala böyle bi bug var mı bilmiyorum ama bu ihtimali de dikkate almakta fayda var.</li><li>API level 26 ve üzeri cihazlarda, APK signing key değişirse, androidId değişebilir. API level 26 altında ise böyle bir durum yoktur.</li></ul><p><a href="https://stackoverflow.com/questions/2785485/is-there-a-unique-android-device-id">Is there a unique Android device ID?</a></p><p><a href="https://developer.android.com/reference/android/provider/Settings.Secure#ANDROID_ID">https://developer.android.com/reference/android/provider/Settings.Secure#ANDROID_ID</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc530c18bd2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why does using LiveData is buggy in some cases and how to solve the problem using SingleLiveEvent ?]]></title>
            <link>https://medium.com/digigeek/why-does-using-livedata-is-buggy-in-some-cases-and-how-to-solve-the-problem-using-singleliveevent-ed24f439ee48?source=rss-830264dd5efb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed24f439ee48</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[ömer iyiöz]]></dc:creator>
            <pubDate>Sat, 27 Feb 2021 07:43:03 GMT</pubDate>
            <atom:updated>2021-04-01T07:33:06.291Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why does using LiveData is buggy in some cases and how to solve the problem using SingleLiveEvent ? Try with examples.</strong></p><p>In this article, i got help from Jose Alcerreca’s great article, and implemented the cases he mentioned.</p><p><a href="https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150">LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case)</a></p><p><strong>Example 1 :</strong></p><p>In the first example we used MutableLiveData. When we clicked the textView, <strong>clickedLiveData.postValue(true)</strong> is called. Thus, the observer is invoked and 2nd activity is launched. Then if you press back button, 1st activity is opened. Then if you rotate the device, 2nd activity is opened. Why ? Because activity is recreated and observer is invoked again. This is a common bug. We should solve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZzdQRAec_u54-d5QGr9jg.png" /></figure><p>To solve the bug in the first example, you can use a <strong>SingleLiveEvent </strong>or <strong>Event wrapper</strong>.</p><ul><li>2nd and 3rd examples show <strong>SingleLiveEvent </strong>usage.</li><li>4th and 5th examples show <strong>Event wrapper </strong>usage.</li></ul><p>1st, 2nd and 4th examples contains a simple textView. When you clicked the textView, liveData.postValue is called thus observer is invoked and next activity is launched. When you press back and rotate the device observer is invoked again in 1st example which causes a bug. In the 2nd and 4th examples, since observer is not invoked, there is no bug.</p><p><strong>Example 2 :</strong></p><p>In the 2nd example we used SingleLiveEvent&lt;Boolean&gt;. When we clicked the textView, <strong>clickedSingleLiveEvent.postValue(true)</strong> is called. Thus, the observer is invoked and 3rd activity is launched. Then if you press back button, 2nd activity is opened. Then if you rotate the device, you are still in the 2nd activity. Although the 2nd activity is recreated after rotation, observer is not invoked again. Thus 2nd activity does not contain the bug which exists in 1st activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WsDPYDVYH9h4XmURIU9EPg.png" /></figure><p>Lets analyze SingleLiveEvent class. When you set a value for SingleLiveEvent, mPending becomes true. Then one of its observer sets mPending value to false and invoked. If there are multiple observers, the other observers are not invoked since mPending is false.</p><p>In other words, if we call setValue of SingleLiveEvent, only one observer is invoked. SingleLiveEvent observers don’t invoke again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1vdHmOlRhiKfq7I8ET6zw.png" /></figure><p><strong>Example 3:</strong></p><p>In the 3rd example we used SingleLiveEvent&lt;String&gt;. We observe SingleLiveEvent from three places(Activity3, Fragment3A, Fragment3B). When</p><pre><strong>_clickedSingleLiveEvent</strong>.<em>value </em>= itemId</pre><p>is called. Only one observer is called as we said earlier. Other 2 observers are not invoked. If you rotate the device, no observer is invoked. But if you call</p><pre><strong>_clickedSingleLiveEvent</strong>.<em>value </em>= itemId</pre><p>again, one observer is invoked again . The other 2 observers are still not invoked.</p><p>If you have multiple observers and you want multiple observers are invoked, please look at the 5th example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aa79MDjvIE17rhQN2wxJkw.png" /></figure><pre><strong>class </strong>SingleLiveEvent&lt;T&gt; : MutableLiveData&lt;T&gt;() {<br><br>    <strong>private val mPending </strong>= AtomicBoolean(<strong>false</strong>)<br><br>    @MainThread<br>    <strong>override fun </strong>observe(owner: LifecycleOwner, observer: Observer&lt;<strong>in </strong>T&gt;) {<br><br>        <strong>if </strong>(hasActiveObservers()) {<br>            Log.w(<strong>TAG</strong>, <strong>&quot;Multiple observers registered but only one will be notified of changes.&quot;</strong>)<br>        }<br><br>        <em>// Observe the internal MutableLiveData<br>        </em><strong>super</strong>.observe(owner, <strong>object </strong>: Observer&lt;T&gt; {<br>            <strong>override fun </strong>onChanged(t: T?) {<br>                <strong>if </strong>(<strong>mPending</strong>.compareAndSet(<strong>true</strong>, <strong>false</strong>)) {<br>                    observer.onChanged(t)<br>                }<br>            }<br>        })<br>    }<br><br>    @MainThread<br>    <strong>override fun </strong>setValue(@Nullable t: T?) {<br>        <strong>mPending</strong>.set(<strong>true</strong>)<br>        <strong>super</strong>.setValue(t)<br>    }<br><br>    <em>/**<br>     * Used for cases where T is Void, to make calls cleaner.<br>     */<br>    </em>@MainThread<br>    <strong>fun </strong>call() {<br>        setValue(<strong>null</strong>)<br>    }<br><br>    <strong>companion object </strong>{<br><br>        <strong>private val TAG </strong>= <strong>&quot;SingleLiveEvent&quot;<br>    </strong>}<br>}</pre><p><strong>Example 4:</strong></p><p>When you clicked the textView,</p><pre><strong>_clickedEvent</strong>.<em>value </em>= Event(itemId)</pre><p>is called. clickedEvent observer is invoked and next activity is launched. Open next activity and press back. When you rotate the device, 4th activity is still seen. There is no bug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3iR34BL9wmPAXhx0izLg9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5XWjVr4aDzDvHK3hDpj6A.png" /><figcaption>Event wrapper class</figcaption></figure><p><strong>Example 5 :</strong></p><p>In the 5th example we used</p><pre>MutableLiveData&lt;Event&lt;String&gt;&gt;()</pre><p>We observe this MutableLiveData from 3 places(Activity5, Fragment5A, Fragment5B). When we clicked textView, the following line</p><pre><strong>_clickedEvent</strong>.<em>value </em>= Event(itemId)</pre><p>is called. All observes are invoked but only two textView value is changed. Here is the details:</p><ul><li>In <strong>activity</strong>, when the observer is invoked, peekContent returns the current string value and textView value is updated.</li><li>In <strong>Fragment5A and Fragment5B</strong>, when the observer is invoked, <strong>getContentIfNotHandled()</strong> is called and <strong>hasBeenHandled</strong> is set to true and returns the content string. When the next <strong>getContentIfNotHandled() </strong>is called, it returns null since <strong>hasBeenHandled</strong> is true. Thus one textView value is updated and one textView value is not updated in <strong>Fragment5a</strong> and <strong>Fragment5b.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AVjjGXsNWVeV-Z0lu24irA.png" /></figure><p>You can try the examples i mentioned in this article by cloning the following repo.</p><p><a href="https://github.com/oiyio/SingleLiveEvent-and-EventWrapper">oiyio/SingleLiveEvent-and-EventWrapper</a></p><p>In this article, i explained why we need a SingleLiveEvent and Event wrapper class. If you liked it, please clap for support.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed24f439ee48" width="1" height="1" alt=""><hr><p><a href="https://medium.com/digigeek/why-does-using-livedata-is-buggy-in-some-cases-and-how-to-solve-the-problem-using-singleliveevent-ed24f439ee48">Why does using LiveData is buggy in some cases and how to solve the problem using SingleLiveEvent ?</a> was originally published in <a href="https://medium.com/digigeek">DigiGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instant app kullanımı — Android]]></title>
            <link>https://medium.com/digigeek/instant-app-kullan%C4%B1m%C4%B1-android-d9bf3f4f591e?source=rss-830264dd5efb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9bf3f4f591e</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[instant-apps]]></category>
            <category><![CDATA[dynamic-feature-module]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[ömer iyiöz]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 13:31:52 GMT</pubDate>
            <atom:updated>2021-02-17T08:48:50.566Z</atom:updated>
            <content:encoded><![CDATA[<h3>Instant app kullanımı — Android</h3><p>Google’ın github’ında paylaştığı app-bundle-samples içerisinde birbirinden farklı dynamic-feature ve instant app örnekleri var.</p><p>En basit bir instant yapabilmek için aşağıdaki linkte verdiğim <strong>aab-simple</strong> isimli projeyi derleyip google play’e instant app kısmından upload edebilirsiniz:</p><p><a href="https://github.com/android/app-bundle-samples/tree/main/InstantApps/aab-simple">android/app-bundle-samples</a></p><p>Bu projenin kodlarını incelerseniz, basit bir hello world uygulama olduğunu tek farkının manifest’deki şu kod olduğunu görebilirsiniz:</p><pre>&lt;dist:module<br>    dist:instant=&quot;true&quot;&gt;<br>&lt;/dist:module&gt;</pre><p>Kodların tamamını aşağıda görebilirsiniz :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbmqI9b0Iu6KrVQqXppzzg.png" /></figure><p>Normal uygulamamızı ve instant app’ımızı bu şekilde iki farklı application module kullanarak sürdüreceksek, instant app ve installable app(normal uygulamamız)’’ımızın build.gradle’ında tanımladığımız <strong>applicationId</strong>’leri aynı olmalıdır.</p><p>Ayrıca instant app’iniz için kullandığınız <strong>versionCode</strong> ve <strong>versionName</strong>, installable app için uygulamanızda kullandığınız <strong>versionCode</strong> ve <strong>versionName</strong>’den mutlaka düşük olmalıdır. Çünkü instant app üzerinden installable app yüklendiğinde app update olmuş gibi düşünebilirsiniz.</p><p><strong>Add release type “Google Play Instant” in Play Store</strong></p><p>Instant app kullanabilmemiz için play store’da Google Play Instant “release type”ını eklemeliyiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibdoaC1j_l0Ftcej4n0J1g.png" /></figure><p>Bunu ekledikten sonra bundle yükleyeceğimiz zaman artık sağ üstte 2 farklı seçenek olacaktır. Normal uygulamamızın bundle’ını Standard seçip upload ederiz. Instant app kullanmak için ise instant apps only seçip buraya ilgili bunle’ı upload ederiz. Yukarıda kodlarını gösterdiğim projenin bundle’ını instant apps only seçerek upload edebilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYfYozOd_bAiGlOquhP7-Q.png" /></figure><p>Test için bundle’ınızı internal testing kısmından upload edebilirsiniz. Tester olarak eklediğiniz email sahipleri play store’dan uygulamanızın internal testing’e eklenmiş sürümlerini görüp yükleyebilirler.</p><p><strong>Dynamic feature module’leri instant app yaparak kullanmak</strong></p><p>Bu başlık altında anlatacaklarım bir önceki makalemde anlattığım dynamic feature modules konusunun devamı niteliğindedir.</p><p>Bu başlık altında Google’ın github’ında paylaştığı app-bundle-samples içerisindeki <strong>DynamicFeatures</strong> projesini inceleyeceğiz.</p><p><a href="https://github.com/android/app-bundle-samples/tree/main/DynamicFeatures">android/app-bundle-samples</a></p><p>Daha önceki makalemde dynamic feature module kullanmaktan bahsetmiştim. Bir dynamic feature module’ü instant app yapmak çok basittir. Yapmamız gereken şey, dynamic feature module’ün manifest dosyasına gidip <strong>dist:instant=”true”</strong> eklemektir. Ayrıca, bu module’ü dynamic feature olarak kullanmak istemediğimiz için, <strong>dist:onDemand=”false”</strong> deriz.</p><pre>&lt;dist:module <strong>dist:instant=&quot;true&quot;</strong> <strong>dist:onDemand=&quot;false&quot;</strong><br>    dist:title=&quot;@string/title_detail_feature&quot;&gt;<br>    &lt;dist:fusing dist:include=&quot;true&quot; /&gt;<br>&lt;/dist:module&gt;</pre><p>Bu örnekte instant app, bir url üzerinden tetiklenmektedir. Ekrandaki bir butona tıklayınca openUrl() method’u çağırılmaktadır. Bu method ise bu url’i intent filter ile dinleyen activity’yi ayağa kaldırmaktadır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XEBtZ6JNvlUGjCFLK66QUg.png" /></figure><p>Bu konuyla ilgili eklememi, düzeltmemi istediğiniz yerler varsa, benimle iletişime geçebilirsiniz.</p><p>Daha fazla makale için, clap’lemeyi unutmayalım :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9bf3f4f591e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/digigeek/instant-app-kullan%C4%B1m%C4%B1-android-d9bf3f4f591e">Instant app kullanımı — Android</a> was originally published in <a href="https://medium.com/digigeek">DigiGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Feature Module kullanımı — Android]]></title>
            <link>https://medium.com/digigeek/dynamic-feature-module-kullan%C4%B1m%C4%B1-android-4e4b00c2a3ce?source=rss-830264dd5efb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e4b00c2a3ce</guid>
            <category><![CDATA[dynamic-feature-module]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[instant-apps]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[multi-module-project]]></category>
            <dc:creator><![CDATA[ömer iyiöz]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 13:25:35 GMT</pubDate>
            <atom:updated>2022-02-09T09:21:49.988Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic Feature Module kullanımı — Android</h3><p>Bu yazımda dynamic feature module’lerden bahsedip, google code lab’da verilen örneği inceleyeceğim.</p><p>Google codelab’da geliştirilen Dynamic feature module örneğinin github link’i üzerinden kodları incelemiştim. Ancak daha sonra bu repo’nun daha güncel halini buldum. Her iki link’i de inceleyebilirsiniz, iki proje de düzgün çalışıyor :</p><ul><li><a href="https://github.com/googlecodelabs/android-dynamic-features">googlecodelabs/android-dynamic-features</a></li><li><a href="https://github.com/android/app-bundle-samples/tree/main/DynamicFeatures">android/app-bundle-samples</a></li></ul><p><a href="https://developer.android.com/guide/app-bundle/play-feature-delivery">https://developer.android.com/guide/app-bundle/play-feature-delivery</a></p><p><strong>App bundle</strong></p><p>Dynamic feature module kullanabilmek için app bundle kullanmak zorundayız.</p><p><strong>Dynamic feature’lar API level 21+ için kullanılabilir</strong></p><p>Dynamic feature module’lerin runtime’da indirilip yüklenmesi işlemini sadece API level 21 ve üzeri cihazlar destekler. API level 20 ve altındaki cihazlarda feature module’lerin kullanılabilir olması için fusing enable edilmelidir. Detay için bu makale içerisinde dist:fusing diye arama yapabilirsiniz.</p><p><strong>Dependency</strong></p><p>Eğer <strong>on-demand module</strong> kullanacaksak, <strong>on-demand module</strong>’ü runtime’da download edebilmek için <strong>SplitInstallManager</strong> class’ını kullanmalıyız. <strong>SplitInstallManager</strong> class’ını kullanabilmek için, bu class’ı kullanacağımız module’e(bu muhtemelen app module olacaktır) aşağıdaki dependency’yi eklemeliyiz :</p><pre>api &quot;com.google.android.play:core:1.9.1&quot;</pre><p><strong>On-demand module </strong>kullanmayacaksanız, bunun yerine <strong>install-time</strong> <strong>module</strong> kullanacaksanız bu dependency’ye ihtiyacınız yoktur.</p><p>Haydi hemen başlayalım. Örnek üzerinde çalışırken teorik bilgileri de vermeye çalışacağım.</p><p>İlk örneğimizdeki projemizde 5 farklı module var. Bunlardan birisi <strong>app(application module) module</strong>, diğer dördü ise <strong>dynamic feature module</strong>’dür. Kullanıcı uygulamayı yüklediğinde sadece <strong>app module</strong>’ü yüklemiş olur. Kullanıcı uygulama içerisinde gezerken bir feature’ı kullanmak istediğinde eğer bu feature dynamic feature module içerisinde tanımlıysa, kullanıcıya bir progress bar gösterip arka planda gerekli dynamic feature module’ün play store’dan indirilmesini sağlayabiliriz.</p><p>Bu örnekte, <strong>app module</strong>, <strong>base module</strong>’ümdür, <em>tüm dynamic feature module’ler bu module’e bağımlıdır</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzSZb1XZIC45ka9ue1H-xA.png" /></figure><p><strong>app module</strong>’ümüzün <strong>build.gradle</strong> dosyasında <strong>dynamic feature module</strong>’leri söyleriz:</p><pre>dynamicFeatures = [&#39;:assets&#39;,<br>                   &#39;:kotlin&#39;,<br>                   &#39;:java&#39;,<br>                   &#39;:native&#39;]</pre><p>Feature module’lerimizin build.gradle dosyalarında yapmamız gereken 2 şey vardır:</p><p><strong>1- apply plugin: ‘com.android.dynamic-feature’</strong></p><p><strong>2- implementation project(‘:app’)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7l0h4lgqTNMmrZBbD6F7Kg.png" /></figure><p><strong>Enable SplitCompat</strong></p><p>Application module’ümüzün, indirilen Dynamic feature module’lere erişebilmesi için <strong>SplitCompat</strong>’ı enable etmeliyiz.</p><p><a href="https://developer.android.com/guide/playcore/play-feature-delivery#enable_splitcompat">https://developer.android.com/guide/playcore/play-feature-delivery#enable_splitcompat</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ivuI8lqIWQRP517ck-OHRw.png" /></figure><p>Bunu yapmanın farklı yolları vardır.</p><p>1- Custom application class’ımız yoksa, manifest’de <strong>SplitCompatApplication</strong> class’ını aplication class’ımız olarak belirtebiliriz.</p><pre>&lt;application<br>    ...<br>    android:name=&quot;<strong>com.google.android.play.core.splitcompat.SplitCompatApplication</strong>&quot;&gt;<br>&lt;/application&gt;</pre><p>2-Custom application class’ımız varsa <strong>SplitCompatApplication</strong> class’ını extend etmesini sağlayabiliriz.</p><pre>class MyApplication : <strong>SplitCompatApplication()</strong> {<br>    ...<br>}</pre><p>3-Custom application class’ımız varsa, ama <strong>SplitCompatApplication</strong> class’ını extend etmek istemiyorsak, ihtiyacımız olan activity’ye aşağıdaki method’u ekleyebiliriz:</p><pre>override fun attachBaseContext(base: Context) {<br>    super.attachBaseContext(base)<br>    // Emulates installation of future on demand modules using SplitCompat.<br>    SplitCompat.install(this)<br>}</pre><p>4- Dynamic Feature module’ümüz(demand modülümüz) instant app’i de destekliyorsa SplitCompat’ı koşullu enable edebiliriz :</p><pre>override fun attachBaseContext(base: Context) {<br>    super.attachBaseContext(base)<br>    if (!InstantApps.isInstantApp(this)) {<br>        SplitCompat.install(this)<br>    }<br>}</pre><p><strong>SplitInstallManager ve SplitInstallStateUpdatedListener instance’ları</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYrztMZRbgTtRj05l9pjig.png" /></figure><p><strong>AndroidManifest.xml dosyaları</strong></p><p>Module’lerimizin AndroidManifest.xml dosyaları aşağıdaki gibidir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjyFcBjX42FrgP46wr-lEQ.png" /></figure><p>Module’lerimiz runtime’da application module tarafından indirilmesi talep edildiğinde indirilip kullanılacak demek aşağıdaki kodları yazdık :</p><pre>&lt;dist:delivery&gt;<br>    &lt;dist:on-demand/&gt;<br>&lt;/dist:delivery&gt;</pre><p><strong>dist:fusing</strong></p><p>Dynamic feature module’lerin indirilip yüklenmesi sadece <strong>Android 5.0(api 21) ve üzeri</strong> cihazlar destekler. api 20 ve altı cihazlarda feature’ınızın kullanılabilir olmasını istiyorsanız, fusing’i enable etmelisiniz, ama bu durumda feature module’ler uygulama kurulurken indirilmiş olacaktır.</p><pre>&lt;dist:fusing dist:include=&quot;true&quot; /&gt;</pre><ul><li>Only devices running Android 5.0 (API level 21) and higher support downloading and installing features on demand. To make your feature available to earlier versions of Android, enable <strong>Fusing</strong> when you create a feature module.</li></ul><p><strong>dist:title ve on-demand module’ün yüklü olup olmadığını check etmek</strong></p><p>bir module’ün yüklü olup olmadığını anlamaya çalıştığımız kısım aşağıda gösterdim. Dynamic feature module’lerin manifest dosyalarında tanımladığımız <strong>dist:title</strong> önemlidir. Çünkü bir module’ün yüklü olup olmadığını check etmek için aşağıdaki method’u çağırırız. contains() method’unun aldığı parametre dist:title’a verdiğimiz değerdir.</p><pre><strong>splitInstallManager.<em>installedModules</em>.contains(name)</strong></pre><p>Yani java isimli dynamic feature module’ümün manifest’inde,</p><pre><strong>dist:title=”my_java_module”</strong></pre><p>dersem, bu module’ün yüklü olup olmadığını check etmek için aşağıdaki kodu kullanmalıyım :</p><pre><strong>splitInstallManager.<em>installedModules</em>.contains(&quot;my_java_module&quot;)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1PJ4Tjo06J3wjsVMVFGAGw.png" /></figure><p><strong>Feature module’ün indirilmesini başlatmak</strong></p><p>Bir on-demand module’ün yüklü olup olmadığını check ettikten sonra, eğer yüklü değilse, SplitInstallRequest instance yaratırız. Bu instance’ı yaratırken addModule() method’una verdiğimiz parametre yüklemek istediğim on-demand module’ün dist-title’ında belirttiğimiz string’dir. SplitInstallManager instance’ının startInstall() method’unu çağırarak download işlemini başlatırız.</p><pre>splitInstallManager.<strong>startInstall</strong>(splitInstallRequest)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Besl7xnjYBkGoRa1I3CWkQ.png" /></figure><p>Download işlemi bittiğinde listener’ımız tetiklenip kotlin isimli on-demand module’ümüzün activity’si launch edilecektir.</p><p><strong>Birden fazla on-demand module’ün tek seferde indirilmesi</strong></p><p>4 farklı on-demand module’ümün title’ı bir listeye koyulur. Sonra herbir module yüklü mü diye bakılır, yüklü olmayan module’lerin title’ları requestBuilder’a eklenip SplitInstallManager instance’ının startInstall() method’u çağırılır.</p><pre>splitInstallManager.<strong>startInstall</strong>(splitInstallRequest)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0LlQO3pQsv-A0G8xNO_aCg.png" /></figure><p>Bir sonraki yazımda instant app’lerden bahsedeceğim.</p><p>Yazılarımızın devamının gelmesi için clap’lemeyi unutmayınız :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e4b00c2a3ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/digigeek/dynamic-feature-module-kullan%C4%B1m%C4%B1-android-4e4b00c2a3ce">Dynamic Feature Module kullanımı — Android</a> was originally published in <a href="https://medium.com/digigeek">DigiGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn MotionLayout step by step — Example 1 : layoutDescription, KeyFrameSet, KeyAttribute…]]></title>
            <link>https://medium.com/digigeek/learn-motionlayout-step-by-step-example-1-layoutdescription-keyframeset-keyattribute-e1353d764836?source=rss-830264dd5efb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1353d764836</guid>
            <category><![CDATA[motionlayout]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[ömer iyiöz]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 05:02:30 GMT</pubDate>
            <atom:updated>2021-03-04T11:42:58.026Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn MotionLayout step by step — Part 1 : layoutDescription, KeyFrameSet, KeyAttribute, framePosition, motionTarget</h3><p>This is an introductory article for MotionLayouts in Android development. We will explore the MotionLayout with code samples step by step.</p><p>At the end of this article, you will learn the usage of keywords i mentioned in the title :</p><ul><li>layoutDescription,</li><li>KeyFrameSet and KeyAttribute,</li><li>framePosition,</li><li>motionTarget</li></ul><p><strong>Dependency</strong></p><p>MotionLayout is a subclass of <a href="https://developer.android.com/training/constraint-layout">ConstraintLayout</a>. The below dependency works for both ConstraintLayout and MotionLayout:</p><pre>implementation &#39;androidx.constraintlayout:constraintlayout:2.0.4&#39;</pre><p><strong>Backwards compatible to API level 14</strong></p><p>MotionLayout is available as a part of the ConstraintLayout library, MotionLayout is available as a support library and is backwards-compatible to <a href="https://developer.android.com/guide/topics/manifest/uses-sdk-element#ApiLevels">API level 14</a>.</p><p>MotionLayouts are really simple. Lets write our first MotionLayout example step by step.</p><p><strong>Example 1</strong></p><p>In this example, we will implement an animation as the following :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*VkrtbWKBFfzbPP0Iz4XZ1A.gif" /><figcaption>Scale of textView increases from 1 to 3 and from 3 to 1 gradually.</figcaption></figure><p>Firstly, we write a very simple activity using constraintLayout. There is no new thing yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_BEP0HaOeY1sVx7CIYPVw.png" /></figure><p>Secondly, change your root view from constraintLayout to MotionLayout. When i do that, MotionLayout has red color. Android studio suggests me to generate MotionScene file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S93bNCELBY131asc3tG-ew.png" /></figure><p>Thirdly, click “Generate MotionScene file”, and <strong>activity_1_scene.xml</strong> file is created under <strong>res/xml/</strong> directory, automatically by Android Studio. You may need to create xml directory manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZq7-U4S5JvDrbHXpmKchg.png" /></figure><p>Now, my project has the following files. When i run the project, i get the same output with the example above. Only a textView is shown. No new thing has come in my application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3_7yGPSYaLAWB4fOvst_Q.png" /></figure><p>Please be aware that, in my activity layout xml file, i will refer to my activity_1_scene file which is generated by Android Studio automatically.</p><p>Fourthly, i will make a small change in activity_scene.xml file and i will achieve an animation. That’s it! The final code looks like as the following :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*geC3MiDtnwFVoXQPLzuXSg.png" /></figure><p>The key points in this example are the followings:</p><ul><li>My animation duration is 10000 miliseconds(10 seconds).</li><li>framePosition can be a number only in the range [0,100], with 1 being 1% through the animation, and 99 being 99% through the animation. It means that animations contain 100 frames. In our example, our animation duration is 10 second so 50th frame is displayed in 5th second.</li><li>Only the view with the id “textView1” animates in this example. In the 50th frame, the scaleX and scaleY of textView1 is 3. I didn’t write KeyAttributes for 0th and 100th frame because in the initial(0th) and final(100th) frame, the scaleX and scaleY of textView1 is 1 by default. If you want, you can write 0th and 100th frame explicity as the following. It works but makes no difference in our animation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rhNyf-oo6OuP-XJOw6EWbw.png" /></figure><p>To sum up,</p><ul><li>while the animation plays from 0th to 50th frame, size of textView1 increases from its original size to the size of 3 times of its original size gradually.</li><li>while the animation plays from 50th to 100th frame, size of textView1 decreases from the size of 3 times of its original size to its original size gradually.</li></ul><p><strong>Example 2</strong></p><p>Example 2 is similar to the example 1. Check the codes :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKDoHROJUp6v7Io17TVWSg.png" /></figure><p>The resulting animation :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*EYRZZZlSCO6fviiVACCjyQ.gif" /><figcaption>Alpha of textView changes from 1 to 0, and from 0 to 1 gradually.</figcaption></figure><p>This is the end of this article. If you like it, please do not forget clapping.</p><p>In the next article, we will learn the use of ConstraintSet and Constraint. Before jumping to the next article, please fully grasp the two examples in this article.</p><p>Happy coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1353d764836" width="1" height="1" alt=""><hr><p><a href="https://medium.com/digigeek/learn-motionlayout-step-by-step-example-1-layoutdescription-keyframeset-keyattribute-e1353d764836">Learn MotionLayout step by step — Example 1 : layoutDescription, KeyFrameSet, KeyAttribute…</a> was originally published in <a href="https://medium.com/digigeek">DigiGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>