<?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 Jast Lai on Medium]]></title>
        <description><![CDATA[Stories by Jast Lai on Medium]]></description>
        <link>https://medium.com/@jastpower884?source=rss-b868b6eecf46------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2xVYeM_4KuPeYho94ejyEA.png</url>
            <title>Stories by Jast Lai on Medium</title>
            <link>https://medium.com/@jastpower884?source=rss-b868b6eecf46------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:27:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jastpower884/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[Something about Kotlin Coroutines]]></title>
            <link>https://medium.com/jastzeonic/something-about-kotlin-coroutines-0a02d188832b?source=rss-b868b6eecf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a02d188832b</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Jast Lai]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 08:24:47 GMT</pubDate>
            <atom:updated>2025-04-12T08:24:47.390Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*aEGk7mwMzpS4fw1S.png" /></figure><p>This is the post I translated from Mandarin to English from this post. If you are interesting. You can see this there.</p><p>I still remember the first time I heard about Coroutines — I was a bit confused, thinking, ‘Wait, what is this new kind of move (lol)? I didn’t pay much attention to it afterward. For quite a while, I just let it slide. Then one day, I ran into an issue where a file I/O operation was blocking the UI thread, and I had to handle it asynchronously. Writing a HandlerThread was something I wanted to avoid (though sometimes it’s just unavoidable), and using Rx always felt like over design for what I needed. Eventually, I looked into Coroutines and decided to give them a try. The bumpy journey that followed is a whole other story.</p><h4>“What problem are we trying to solve?”</h4><pre>functionA()<br>functionB()<br>functionC()</pre><p>Under normal circumstances, the execution order is straightforward: functionA() → functionB() → functionC().</p><p>If everything runs on a single thread, this flow works smoothly without issues.</p><p>But let’s say this is running on the main thread, and functionA depends on the result from another thread—one that takes a long time to process before it can return that result. Let’s call it the IO thread for now. That means functionA has to wait for the IO thread to finish and return the result before it can proceed, which in turn delays functionB, and only after that comes functionC.</p><p>During that waiting time, the main thread can’t do anything else — it just sits there idling.</p><p>If this happens on the Android main thread, the UI will freeze. If it takes even slightly too long, the system will throw an ANR (Application Not Responding) error and forcefully kill the app, assuming it’s crashed.</p><p>There are actually many ways to handle this kind of asynchronous problem, like writing your own callback, managing a HandlerThread, or using Rx to subscribe and observe. But sometimes these approaches feel unintuitive or overly complex—like using a sledgehammer to crack a nut.</p><p>So, is it possible to write code just like the simple flow above, and when functionA is waiting on the IO thread, let the main thread go do other tasks? Then, once the IO thread finishes its job, it can come back and continue executing functionA, then functionB, and finally functionC?</p><p>Yes — it’s possible. And that solution is Coroutines.</p><h4>“So, what exactly are Coroutines?”</h4><p>Coroutines’ is a combination of the words ‘cooperation’ and ‘routine’, referring to a form of cooperative execution in a program.</p><p>Then… Who’s cooperating with whom? What kind of program are we talking about? Blah blah blah… and suddenly, a bunch of questions start popping up in our heads.</p><p>Well, ‘routine’ refers to a function or method being called during program execution. In other words, Coroutines are about having functions or methods working together — cooperatively — with other functions or methods.</p><p>Still sounds kind of abstract, isn’t? What exactly are they cooperating <em>on</em>?</p><p>Well, that leads us to one of the defining features of Coroutines: they allow a method to be <em>suspended</em> during execution and then <em>resumed</em> later. And what’s really cool is that the state of the method can be preserved during suspension, so when it resumes, it continues right where it left off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/0*uhrR2Y0qZvCHxmkq.png" /></figure><p>In other words, when I’m on the main thread running functionA, and I need to wait for the result from the IO thread (which takes a long time), I can temporarily pause functionA. I then allow the main thread to handle other tasks. Once the IO thread finishes processing and returns the result, functionA can resume execution and continue, eventually giving me the result I need. This is the concept of Coroutines. Doesn’t that sound pretty great?</p><p>In fact, this concept was first proposed back in 1964. Many programming languages have adopted similar concepts, but in Android, such approaches weren’t widely promoted until Kotlin became the official language. After that, Coroutines gained popularity in the Android community when they were introduced as part of the Support Library.</p><h4>Kotlin Coroutines</h4><pre>dependencies {<br>    implementation(&quot;org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2&quot;)<br>}</pre><p>The current version is 1.10.1, it’s updated all the time. You can check laterst version <a href="https://github.com/Kotlin/kotlinx.coroutines">here</a>.</p><p>Since this is used on Android, the main thread in Android is a bit different from regular Java, so it requires a different implementation. Otherwise, you’ll run into errors.</p><pre>implementation(&quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2&quot;)</pre><p>After we have done this, we can begin to use it.</p><h4>A simple start.</h4><p>What I want to do here is have a countdown Text on the screen, which can be easily done using Coroutines.</p><pre>class CoroutineActivity : AppCompatActivity() {<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_coroutine)<br>        GlobalScope.launch(Dispatchers.Main) {<br><br>            for (i in 10 downTo 1) { <br>                textView.text = &quot;count down $i ...&quot; // update text<br>                delay(1000) <br>            }<br>            textView.text = &quot;Done!&quot;<br>        }<br>    }<br><br>}</pre><p>And it will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/0*fiC36fGxqKWX_p1b.gif" /></figure><p>If you want the same result with a Thread{}, you can write it like this:</p><pre>Thread {<br>    for (i in 10 downTo 1) {<br>        Thread.sleep(1000)<br>        runOnUiThread {<br>            textView.text = &quot;count down $i ...&quot; <br>        }<br>    }<br>    runOnUiThread {<br>        textView.text = &quot;Done!&quot;<br>    }<br><br><br>}.start()</pre><p>Of course, it will cause some issues. At least now, this won’t immediately throw an Exception (the most common one being an Exception that pops up when the user leaves the screen). However, just because you’re using Coroutines doesn’t mean these issues won’t happen. Remember, there’s no real superiority between these approaches; it’s all about choosing the one that works for you.</p><p>Back to Coroutines — just like with Threads, there are times when we might want to temporarily pause them. In this case, GlobalScope.launch returns something called a Job class.</p><pre>val job: Job = GlobalScope.launch(Dispatchers.Main) {<br>    // launch coroutine in the main thread<br>    for (i in 10 downTo 1) { // countdown from 10 to 1<br>        textView.text = &quot;count down $i ...&quot; // update text<br>        delay(1000) // wait half a second<br>    }<br>    textView.text = &quot;Done!&quot;<br>}</pre><p>If you want to pause it, just use cancel.</p><pre>job.cancel()</pre><p>However, it’s important to note that it won’t stop immediately. It will only be stoped once the task reaches the next suspend method.</p><p>In this case, It will be stoped before the delay(1000).</p><h4>Scope</h4><p>What is GlobalScope?</p><p>In this context, ‘scope’ refers to the range in which Coroutines are active. Whether it’s on the main thread, the IO thread, or if you want to create more worker threads, it can be controlled within a specific control flow, such as the lifecycle of an Activity.</p><p>In principle, any method marked with suspend in Kotlin (which we’ll discuss later) will be within a scope, so you can control the progress and lifetime of the Coroutine.</p><p>The example mentioned here, GlobalScope, is a subclass of CoroutineScope. It’s an implementation of CoroutineScope, and its concept is the highest-level Coroutine. Its scope follows the lifecycle of the entire application. Essentially, its behavior is similar to Dispatchers.Unconfined (which we’ll discuss later too). Using it helps prevent Coroutines from being prematurely terminated, but it’s important to note that it’s like directly calling a static function, so you should be cautious.</p><p>What about directly implementing CoroutineScope?</p><pre>class CoroutineActivity : AppCompatActivity(), CoroutineScope {<br>    override val coroutineContext: CoroutineContext<br>        get() = TODO(&quot;not implemented&quot;)<br>//...ignore<br>}</pre><p>That requires implementing a CoroutineContext. So what exactly is that? It refers to the context in which the Coroutine operates. Here, you can specify whether it runs on the main thread, or simply assign it a Job directly.</p><pre>class CoroutineActivity : AppCompatActivity(), CoroutineScope {<br>    override val coroutineContext: CoroutineContext<br>        get() = job<br><br>    private val job = Job()//...ignore}</pre><p>When you use launch, it will operate with the assigned Job. If you don’t explicitly define it, the job will run on a worker thread by default. Trying to update the UI from there will throw an Exception. You can adjust this behavior based on your needs.</p><p>However, more often than not, I want it to run on the main thread. Kotlinx Coroutines provides an implementation of CoroutineScope called MainScope for this purpose.</p><pre>class AndroidActivity {<br>  private val scope = MainScope()<br>  override fun onDestroy() {<br>     super.onDestroy()<br>     scope.cancel()<br>   }<br>}</pre><p>Or maybe you want it more simplify.</p><pre>class MyActivity : AppCompatActivity(), CoroutineScope by MainScope() {<br>  override fun onDestroy() {<br>    cancel()<br>  }<br>}</pre><p>But take note: what I’m showing here is just a sample. In Android, AppCompatActivity has its own lifecycleOwnerScope, so we usually don’t manage Coroutines this way.</p><h4>Job</h4><p>We’ve mentioned Job quite a few times above. Literally, it means &#39;work&#39;—and in fact, that’s exactly what it represents.</p><p>So what exactly is a Job? From a scope’s perspective, a scope can manage all the Coroutines under it. But the reverse is also true: if I cancel the scope, all its Coroutines will be cancelled as well. That kind of all-or-nothing approach might not always be ideal. So is there a way to control a specific Coroutine directly?</p><p>Actually, you might have noticed that when you call the scope’s launch extension, it returns a Job.</p><p>Yes, a Job. A Job <em>is</em> a Coroutine. More precisely, a Job represents the lifecycle of a single Coroutine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/0*DpIQHwk97bsm3JCY.png" /><figcaption>a fancy little comment.</figcaption></figure><h4>CoroutineContext</h4><p>Talking about ‘Context’ always gives me a bit of a headache. Literally, ‘context’ means the surrounding text or situation. Side note: I personally tend to confuse <em>context</em> with <em>scenario</em> — the latter covers a broader range and usually includes the context itself.</p><p>In this case, ‘Context’ can be thought of as the relationship or environment around a Coroutine. More specifically, CoroutineContext is basically a collection or registry of all the elements that a Coroutine uses. You can assign various elements to it, and retrieve them when needed.</p><p>So what’s the relationship between Scope, CoroutineContext, and Job? In the most basic scenario, a Scope contains a CoroutineContext, and the CoroutineContext contains a Job.</p><p>It’s clear that Job is an element of CoroutineContext, no problem there. But the relationship between Scope and CoroutineContext is a bit more abstract. It touches on the concept of parent-child hierarchies. Here&#39;s the interesting part: what happens when two child contexts are combined? That’s right—they get wrapped into a new Coroutine, which includes a new Job, a new CoroutineContext, and a new parent Scope that encompasses them both.</p><p>It’s a bit hard to grasp at first, but don’t worry — this part doesn’t have much of an impact on daily use. You can take your time to digest it. If you’re curious, you can check out this article:</p><p><a href="https://elizarov.medium.com/coroutine-context-and-scope-c8b255d59055">Coroutine Context and Scope</a></p><h4>Dispatcher</h4><p>So, what’s a Dispatcher supposed to be?</p><p>The word ‘dispatcher’ literally means someone who assigns tasks. In this case, it’s a fully wrapped and ready-to-use CoroutineContext element that makes it easier for developers to manage Coroutine execution. One important thing to note: the behavior of Dispatchers can vary across platforms, as their definitions are based on feature requests.</p><p>In kotlinx.coroutines, there are four built-in Dispatchers:</p><ul><li><strong>Dispatchers.Main</strong>: A wrapper around the Main thread. On Android, this is usually used when you need to perform operations on the UI thread.</li><li><strong>Dispatchers.Default</strong>: The default Dispatcher (not to be confused with CoroutineStart.DEFAULT). It uses the default CoroutineScheduler and typically runs on a background thread—not the Main thread.</li><li><strong>Dispatchers.IO</strong>: This is an enhanced version of Default, optimized for IO-bound tasks. The main difference is the number of threads it opens. Default typically uses N threads (where N is based on the JVM and system resources), while IO allows up to 64 threads by default—and even more if the JVM permits. Both Default and IO are meant to handle long-running or heavy operations without blocking the Main thread.</li><li><strong>Dispatchers.Unconfined</strong>: As the name suggests, it&#39;s not confined to any particular thread. It starts in the current thread where the Coroutine is launched but can resume in a different thread after a suspension point. So be cautious when using it.</li></ul><p>For example, MainScope has a CoroutineContext composed of supervisorJob() + Dispatchers.Main. We’ll ignore supervisorJob() for now—it’s basically a container for structured concurrency. So effectively, MainScope gives you a scope that runs on the Main thread.</p><p>If you call launch() without passing any parameters, it uses the CoroutineContext defined in the current CoroutineScope.</p><p>On Android, Dispatchers.Main will launch the Coroutine on the UI thread, while Dispatchers.IO will launch it on a background thread (a worker thread). This setup lets you determine the execution context in a straightforward way.</p><p>Let’s say I want to read a large file from an SD card. Since this can take some time and, by convention (?), we shouldn’t block the UI thread, I’ll need to use a worker thread to handle the operation. The code would look like this:</p><pre>class CoroutineActivity : AppCompatActivity() {<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_coroutine)<br><br><br>        lifecycleScope.launch(Dispatchers.Main) {<br>            progressBar.visibility = View.VISIBLE<br>            readSomeFile()<br>            progressBar.visibility = View.GONE<br>        }<br>    }<br>}</pre><h4>Suspend</h4><p>Huh? But looking at the code above, it seems like everything is still running on the main thread.</p><p>And this is where we introduce the true essence of Coroutines — the iconic suspend.</p><p>At this point, my readSome function is written like this:</p><pre>suspend fun readSomeFile() = withContext(Dispatchers.IO) {<br> // read some file<br>}</pre><p>withContext(Dispatchers.IO) — as the name suggests — is used to run the task on a Worker thread.</p><p>Also, you’ll notice that this function is marked with suspend at the beginning. That’s pretty straightforward — it means this function can be <em>suspended</em> during its execution.</p><p>What does that mean? Suspend? Doesn’t that just <em>stop</em> the function?</p><p>Remember what we talked about earlier? I want this function to pause after handing off a time-consuming task to another thread. That way, the thread running this function (usually the main/UI thread) can be freed up to do other things. And that’s exactly what’s happening here.</p><p>In other words, initially, we let the UI thread display a ProgressBar. Then we call readSomeFile. Inside readSomeFile, the actual file-reading task is handed over to an IO thread, while the function itself suspends, releasing the UI thread to do other work.</p><p>Once the IO thread finishes reading the large file, the function resumes, continues execution, and we hide the ProgressBar.</p><p>And because of this suspension behavior, any function marked with suspend must be called within a coroutine scope like launch, runBlocking, or from within another suspend function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*ZuspCjj5hoxDyz27.png" /></figure><h4>There are still a couple of things…</h4><p>We’ve used launch and withContext above. Based on a friend&#39;s suggestion, using MainScope might cause some confusion, so I&#39;ll simplify things here and write an example using IntelliJ IDEA.</p><h4>Aync</h4><p>Let’s briefly talk about async. You can call async directly through a scope. The main difference between async and launch is that calling async returns something called Deferred, instead of a Job.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2Fxaj_2QmjM%3Ftheme%3Ddarcula%26from%3D4&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2Fxaj_2QmjM%3Ftheme%3Ddarcula%26from%3D4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/e25bd8ae5025de13f9f7d04bb6b582d6/href">https://medium.com/media/e25bd8ae5025de13f9f7d04bb6b582d6/href</a></iframe><p>Deferred, as the name suggests, refers to something that is deferred. The concept is somewhat similar to Future. The advantage of this approach is that it allows you to make a long-running call only once. So, how do you actually get the data from it? Deferred provides a method called await().</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FuNN0Jfo9bS%3Ffrom%3D4&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FuNN0Jfo9bS%3Ffrom%3D4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2d0da46d82e529278b3207bc18a46b4/href">https://medium.com/media/f2d0da46d82e529278b3207bc18a46b4/href</a></iframe><p>Actually, you’ll notice that await cannot be called directly because it is a suspend function. This means it needs to pause and wait for a while, so it must be called within a coroutine.&quot;</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FcVJ1FHFGi%3Ffrom%3D4&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FcVJ1FHFGi%3Ffrom%3D4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/51b809059ba4137db61b24134ca4a3e7/href">https://medium.com/media/51b809059ba4137db61b24134ca4a3e7/href</a></iframe><p>After calling await, you can get the result.</p><p>This is a common usage in Goroutines and SwiftCoroutines, and you might see a similar approach in Dart as well.</p><p>Additionally, one important feature of async is that it is concurrent. The <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html">official documentation</a> hints at this subtly. I only realized it when I was researching flow one day, and saw a bunch of operators marked as &#39;experiment&#39;. I started complaining about how to use them, and suddenly came across a tutorial that mentioned <a href="https://kotlinlang.org/docs/reference/coroutines/composing-suspending-functions.html#concurrent-using-async">this</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2F_PzIrigGH%3Ftheme%3Ddarcula%26from%3D4&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2F_PzIrigGH%3Ftheme%3Ddarcula%26from%3D4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/7092309789cf3f983000f43195973c52/href">https://medium.com/media/7092309789cf3f983000f43195973c52/href</a></iframe><p>But since it’s called async, it&#39;s clearly an abbreviation for asynchronous, which might already represent its meaning literally.</p><p>However, it actually works quite similarly to launch. Both async and launch will immediately execute the block after being called. The difference is that launch doesn&#39;t return a Deferred to hold the final result, while Deferred allows you to wait for the result. This means that within a coroutine, you can use async to launch multiple concurrent time-consuming tasks, and then use await to wait for their results, achieving concurrency.</p><h4>runBlocking</h4><p>Let’s talk about runBlocking.</p><p>It really does block the thread, which is exactly its purpose. Its goal is to ensure sequential flow rather than parallelism, which is the biggest difference between runBlocking and launch or async.</p><p>The two most intuitive examples would be like this: Let’s say I use two launch functions:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FFbEfu4bKud%3Ftheme%3Ddarcula%26from%3D10&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FFbEfu4bKud%3Ftheme%3Ddarcula%26from%3D10&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad278ff730cf23da7f173c28762a4575/href">https://medium.com/media/ad278ff730cf23da7f173c28762a4575/href</a></iframe><p>What if I use runBlocking?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FNTjyOKCUv%3Ftheme%3Ddarcula%26from%3D10&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FNTjyOKCUv%3Ftheme%3Ddarcula%26from%3D10&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aea4855202cf8a7bced445cc90c68ae/href">https://medium.com/media/1aea4855202cf8a7bced445cc90c68ae/href</a></iframe><p>Due to the difference in seconds, the results would be completely reversed. This actually highlights the difference between concurrency and sequential execution.</p><p>By the way, if you call runBlocking directly on the Android UI thread using Dispatchers.Main, it will freeze the entire app. It will pause the UI thread, and then no one will wake it up.</p><h4>Conclusion</h4><p>This is a simple introduction to the use of Kotlin Coroutines. In fact, Coroutines are so simple to use that it feels a bit guilty, but once you’re familiar with how they work, they really make things much easier. Although I mentioned earlier that I’d prefer to avoid using handlers, if you look closely, you’ll find that Kotlinx Coroutines on Android are still based on threads and handlers (see kotlinx.coroutines.android.HandlerDispatcher). The backend of Kotlin Coroutines is essentially a state machine written in a continuation-passing style, along with handlers to switch between threads. The comments later are quite insightful, but I won’t elaborate on them here.</p><p>If you have any questions or notice any mistakes in my writing, please feel free to ask or correct me. Your feedback and responses are the biggest motivation for me, a fringe person, to keep writing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a02d188832b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jastzeonic/something-about-kotlin-coroutines-0a02d188832b">Something about Kotlin Coroutines</a> was originally published in <a href="https://medium.com/jastzeonic">Jastzeonic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Something about migrating LiveData to Flow]]></title>
            <link>https://medium.com/jastzeonic/something-about-migrating-livedata-to-flow-6e5613ea55d2?source=rss-b868b6eecf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e5613ea55d2</guid>
            <category><![CDATA[andoird]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[flow]]></category>
            <dc:creator><![CDATA[Jast Lai]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 10:48:57 GMT</pubDate>
            <atom:updated>2023-09-23T23:01:01.223Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDZA49bE_NcxIzrbi85VZw.jpeg" /></figure><p>We usually hear that Kotlin’s Coroutines’s Flow can replace the Android Jetpack Compose liveData. Is that true?</p><p>It’s. It’s pretty simple to use Flow to replace the LiveData.</p><p>For example, we have ViewModel called SampleViewModel, which has a LiveData</p><pre>class SampleViewModel : ViewModel() {<br>  val liveData: MutableLiveData&lt;String&gt; = MutableLiveData()<br>}</pre><p>We usually use LiveData comes from ViewModel in Activity like this:</p><pre>viewModel.liveData.observe(this) {<br>    Log.i(&quot;SampleDemo&quot;, &quot;liveData observe : $it&quot;)<br>}</pre><p>Or in Fragment</p><pre>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>  super.onViewCreated(view, savedInstanceState)<br>  viewModel.liveData.observe(viewLifecycleOwner) {<br>    Log.i(&quot;SampleDemo&quot;, &quot;liveData observe : $it&quot;)<br>  }<br>}</pre><p>You want to replace it to become the Flow. I should use StateFlow. It should fit the LiveData trait.</p><pre>class SampleViewModel : ViewModel() {<br>    val stateFlow: MutableStateFlow&lt;String&gt; = MutableStateFlow(&quot;Test&quot;)<br>}</pre><p>We usually use StateFlow comes from ViewModel in Activity like this:</p><pre>lifecycleScope.launch {<br>    viewModel.stateFlow.collect{<br>        Log.i(&quot;SampleDemo&quot;, &quot;state flow collect :$it&quot;)<br>    }<br>}</pre><p>Or we can make it simple by using syntactic sugar:</p><pre>viewModel.stateFlow.onEach {<br>    Log.i(&quot;SampleDemo&quot;, &quot;state flow collect :$it&quot;)<br>}.launchIn(lifecycleScope)</pre><p>It’s similar; use it in the Fragment. You need to use the correct coroutine scope:</p><pre>viewModel.stateFlow.onEach {<br>    Log.i(&quot;SampleDemo&quot;, &quot;state flow collect :$it&quot;)<br>}.launchIn(viewLifecycleOwner.lifecycleScope)</pre><p>In this case, the result will be assigned to LiveData and emitted by a flow a few seconds after the Activity is created.</p><p>This shows a difference between LiveData and StateFlow: LiveData doesn’t have a default value; StateFlow has a default value.</p><p>Then, if we give liveData a default value, is it the same as StateFlow?</p><pre>val liveData: MutableLiveData&lt;String&gt; = MutableLiveData(&quot;Test&quot;)</pre><p>None. If we use the lifecycle.currentState to observe the observer invoke timing:</p><pre>viewModel.liveData.observe(this) {<br>    Log.i(&quot;SampleDemo&quot;, &quot;lifecycle.currentState : ${lifecycle.currentState}&quot;)<br>    Log.i(&quot;SampleDemo&quot;, &quot;liveData observe : $it&quot;)<br>}</pre><pre>viewModel.stateFlow.onEach {<br>    Log.i(&quot;SampleDemo&quot;, &quot;viewModel.stateFlow ${lifecycle.currentState}&quot;)<br>    Log.i(&quot;SampleDemo&quot;, &quot;state flow collect :$it&quot;)<br>}.launchIn(lifecycleScope)</pre><p>Here is what it runs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxcMG4dW4e4uHvZRn3ibOw.png" /></figure><p>You can see the difference between StateFlow and LiveData. The Flow collects its default value at the first init, but the LiveData notifies the observer while the first value is assigned.</p><p>Another important thing that should be noticed is that asynchronous tasks, like API requests, are still running, and you let Activity enter into the background. Then, You receive the result while your Activity state is after onStop.</p><p>I do this at my viewModel</p><pre>viewModelScope.launch {<br>    delay(5000)<br>    liveData.value = &quot;Testing&quot;<br>    stateFlow.value = &quot;Testing&quot;<br>}</pre><p>I delayed five seconds to leave enough time to press home to let the Activity enter the background.</p><p>Then we will get the message like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TouDvpjJZjIP0EQO0BPv7g.png" /></figure><p>The flow collection can still be invoked even if the Activity’s state is onStop.</p><p>Then, you resume the Activity back to the foreground. The LiveData received the later result received.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPcDGgj_2pdIF8VxIOxAYQ.png" /></figure><p>Here is the most significant difference:</p><p>We see. The Flow collected almost immediately after its launch, but LiveData noticed its observer after onStart.</p><p>The Flow doesn’t seem like LiveData received the result while the Activity stopped and notified the observer after the Activity restarted. Flow won’t care about the Activity lifecycle in the background or foreground. It will keep collecting until the Activity is destroyed. This might cause some performance problems (Update the view state that is unnecessary. although it’s very tiny that the user is hard to notice.)</p><p>So, if you want to ensure the StateFlow collect timing is the same as the LiveData observer notice timing. You will need to use launchWhenStarted:</p><pre>lifecycleScope.launchWhenStarted {<br>    viewModel.stateFlow.collect{<br>      Log.i(&quot;SampleDemo&quot;, &quot;flow current lifecycle state  ${lifecycle.currentState}&quot;)<br>      Log.i(&quot;SampleDemo&quot;, &quot;flow launchWhenStarted $it&quot;)<br>    }<br>}</pre><p>So sad. Because it’s beautiful if we can use launchIn, for me, I may write an extension for this like:</p><pre>fun &lt;T&gt; Flow&lt;T&gt;.launchInWhenStarted(scope: LifecycleCoroutineScope): Job = scope.launchWhenStarted {<br>    collect() // tail-call<br>}</pre><p>So I can write it like launchIn Format:</p><pre>viewModel.stateFlow.onEach <br>  Log.i(&quot;SampleDemo&quot;, &quot;flow current lifecycle state  ${lifecycle.currentState}&quot;)<br>  Log.i(&quot;SampleDemo&quot;, &quot;flow launchWhenStarted $it&quot;)<br>}.launchInWhenStarted(lifecycleScope)</pre><p>And here is the other difference. If we emit and assign the value like this:</p><pre>viewModelScope.launch {<br>  stateFlow.value = &quot;Test&quot;<br>  liveData.value = &quot;Test&quot;<br>}</pre><p>Then we got the result like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NoLCgbOcXIUGipsih1cVw.png" /></figure><p>You can see that Flow works just like LiveData.</p><p>But…</p><p>The launchWhenX serial has been deprecated. You might notice it while you use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgdeBYjMICV-0qpIwEgr0Q.png" /></figure><p>Why? Why? I keep asking about it. But I don’t get a satisfying answer. Accroding the documentation in the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cu78RWN98LctazdZqpPwuw.png" /></figure><p>It can lead to wasted resources in some cases. So, it has been deprecated. But What cases? LiveData keeps their observers while Activity is in the background, too. Isn’t it? Nice job, Google.</p><p>Well, After I did some research on this <a href="https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda">post</a>. I realize why this method has been deprecated.</p><p>The Flow may produce the data in hot observable form. e.g.:</p><pre>val simpleFlow = channelFlow {<br>    while (true) {<br>        Log.i(&quot;SampleDemo&quot;, &quot;run in flow&quot;)<br>        delay(1000) // represent some long time process<br>        send(&quot;Test&quot;)<br>    }<br>}.flowOn(Dispatchers.IO)</pre><p>And we collect it by launchWhenStarted this:</p><pre>lifecycleScope.launchWhenStarted {<br>    viewModel.simpleFlow.collect {<br>        Log.i(&quot;SampleDemo&quot;, &quot;flow current lifecycle state  ${lifecycle.currentState}&quot;)<br>        Log.i(&quot;SampleDemo&quot;, &quot;flow launchWhenStarted $it&quot;)<br>    }<br>}</pre><p>Then there is the log:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQv2VhBTVOd8Esy6IKLg6A.png" /></figure><p>We see. The Flow will keep processing even though the Activity has already stopped. It’s truly causing some potential wasted resources when you use the launchWhenStarted .</p><p>So, That’s the reason why launchWhenX serial has been deprecated. The document recommends replacing the launchWhenX serial to repeatOnLifecycle.</p><p>But this literally has more difference with LiveData observation.</p><pre>lifecycleScope.launch {<br>    repeatOnLifecycle(Lifecycle.State.STARTED) {<br>        viewModel.stateFlow.collect {<br>            Log.i(&quot;SampleDemo&quot;, &quot;flow repeatOnLifecycle current lifecycle state ${lifecycle.currentState}&quot;)<br>            Log.i(&quot;SampleDemo&quot;, &quot;flow repeatOnLifecycle $it&quot;)<br>        }<br>    }<br>}</pre><p>Or you may use syntactic sugar:</p><pre>viewModel.stateFlow.flowWithLifecycle(lifecycle,Lifecycle.State.STARTED).onEach {<br>    Log.i(&quot;SampleDemo&quot;, &quot;flow repeatOnLifecycle current lifecycle state ${lifecycle.currentState}&quot;)<br>    Log.i(&quot;SampleDemo&quot;, &quot;flow repeatOnLifecycle $it&quot;) <br>}.launchIn(lifecycleScope)</pre><p>Here is what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBpkV5acmNCrvMK4oSWhsQ.png" /></figure><p>You can see <strong>the Flow collected whenever the Activity restarts.</strong> Not just like the liveData notifies its observer only when the data is updated.</p><p>And if you use it at the wrong lifecycle step, like launching it at onStart.</p><pre>override fun onStart() {<br>    super.onStart()<br>    Log.i(&quot;SampleDemo&quot;, &quot;onStart&quot;)<br>    lifecycleScope.launch {<br>        repeatOnLifecycle(Lifecycle.State.STARTED) {<br>            viewModel.stateFlow.collect {<br>                Log.i(&quot;SampleDemo&quot;, &quot;flow repeatOnLifecycle current lifecycle state ${lifecycle.currentState}&quot;)<br>                Log.i(&quot;SampleDemo&quot;, &quot;flow repeatOnLifecycle $it&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>It will have a lot of collections at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0h74BYKHmNJGHUDHMw4QOQ.png" /></figure><p>But the IDE will warn you when you’re doing this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjWLKW58rEQNNK_kD9EzxQ.png" /></figure><h4>Summary</h4><p>The Flow can replace the LiveData. But If you want to replace the LiveData. You will need to notice different traits between LiveData and Flow. Those two have different development logic.</p><p>Those two things are similar but essential differences. LiveData represents the UI state. StateFlow can represent the UI state and more.</p><p>In my opinion. The Flow is suitable at Jetpack Compose. The LiveData is suitable for Android Views.</p><p>So, if you’re using LiveData a lot in the current project, I suggest you keep using it. You don’t need to change or migrate to flow without any reason.</p><p>But if you start a new project and want to try a new thing and different design and development logic. I will suggest using Stateflow and SharedFlow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e5613ea55d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jastzeonic/something-about-migrating-livedata-to-flow-6e5613ea55d2">Something about migrating LiveData to Flow</a> was originally published in <a href="https://medium.com/jastzeonic">Jastzeonic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Something about The Hilt]]></title>
            <link>https://medium.com/jastzeonic/something-about-the-hilt-144851dacd59?source=rss-b868b6eecf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/144851dacd59</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[dagger]]></category>
            <category><![CDATA[hilts]]></category>
            <dc:creator><![CDATA[Jast Lai]]></dc:creator>
            <pubDate>Sat, 24 Jun 2023 11:36:03 GMT</pubDate>
            <atom:updated>2023-06-24T11:36:03.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*WjvTuY824Drq4tSiT_SiJQ.jpeg" /></figure><h4>foreword</h4><p>We all know we have a dependency injection in Android development called Dagger. And Hilt is also a dependency injection library in Android Development. What&#39;s the difference between those two? Why do we use Hilt, not just Dagger?</p><p>Why don&#39;t we use Dagger?</p><p>The Hilt is a dependency injection library for Android. More precisely to say about it is: Hilt is a dependency injection library for Android that reduces the boilerplate of doing manual dependency injection in your project.</p><p>For example, if we want to inject a module into an Activity, We will do like this:</p><p>I got an interface</p><pre>interface MaskInterface {<br>}</pre><p>I want to inject it into an Activity:</p><pre>class MainActivity : AppCompatActivity() {<br>  private lateinit var appBarConfiguration: AppBarConfiguration<br>  private lateinit var binding: ActivityMainBinding<br>  @Inject lateinit var mask: MaskInterface<br>  override fun onCreate(savedInstanceState: Bundle?) {<br>    WindowCompat.setDecorFitsSystemWindows(window, false)<br>    super.onCreate(savedInstanceState)<br>  }<br>}</pre><p>I wish it could be implemented like this.</p><pre>class InjectionClass : MaskInterface {<br>}</pre><p>So I define a way to provide the implementation.</p><pre>@Module<br>class ProviderModule {<br><br>  @Provides<br>  fun provide(): MaskInterface {<br>    return InjectionClass()<br>  }<br>}</pre><p>And I must tell Dagger we want to inject this module into this Activity. So that Dagger would know what it should generate:</p><pre>@Singleton<br>@Component(modules = [ProviderModule::class])<br>interface ApplicationComponent {<br>  fun inject(activity: MainActivity)<br>}</pre><p>After that. We can finally inject the interface.</p><pre>class MainActivity : AppCompatActivity() {<br>  private lateinit var appBarConfiguration: AppBarConfiguration<br>  private lateinit var binding: ActivityMainBinding<br>  @Inject lateinit var mask: MaskInterface<br>  override fun onCreate(savedInstanceState: Bundle?) {<br>    WindowCompat.setDecorFitsSystemWindows(window, false)<br>    super.onCreate(savedInstanceState)<br>    DaggerApplicationComponent.create().inject(this)<br>  }<br>}</pre><p>This is quite bothering, isn&#39;t it?</p><p>Then… How about the Hilt?</p><h4><strong>How should we start?</strong></h4><p>Of course, we will need to set some things.</p><p>In the application grade:</p><pre>plugins {<br>   …<br>  id &#39;com.google.dagger.hilt.android&#39; version &#39;2.44&#39; apply false<br>}</pre><p>In the app grade:</p><pre>plugins {<br>  …<br>  id &#39;kotlin-kapt&#39;<br>  id &#39;com.google.dagger.hilt.android&#39;<br>}<br>dependencies {<br>  implementation &quot;com.google.dagger:hilt-android:2.44&quot;<br>  kapt &quot;com.google.dagger:hilt-compiler:2.44&quot;<br>}<br>// Allow references to generated code<br>kapt {<br>  correctErrorTypes true<br>}</pre><p>Then we need to set the Application first:</p><pre>@HiltAndroidApp<br>class AppApplication : Application()</pre><p>Or we will get an error :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5kJqbJe7BpIprb2m" /></figure><p>The reason is simple if we don&#39;t have the Hitlapplication. Then we don&#39;t have any instance to generate any instance you want to inject.</p><h4><strong>How to inject instances in Activity?</strong></h4><p>We can use @AndroidEntryPoint annotation to tell Hilt we have some object that needs to be injected in a certain control flow.</p><pre>@AndroidEntryPoint<br>class MainActivity : AppCompatActivity() {<br>  private lateinit var appBarConfiguration: AppBarConfiguration<br>  private lateinit var binding: ActivityMainBinding<br>  @Inject lateinit var mask: MaskInterface<br>  override fun onCreate(savedInstanceState: Bundle?) {<br>    WindowCompat.setDecorFitsSystemWindows(window, false)<br>    super.onCreate(savedInstanceState)<br>  }<br>}</pre><p>And you will still need to add a provider, or Hilt won&#39;t find the method to generate an instance of your statement.</p><pre>@Module<br>@InstallIn(ActivityComponent::class)<br>class ProviderModule {<br>  @Provides<br>  fun provide(): MaskInterface {<br>    return InjectionClass()<br>  }<br>}</pre><p>If we use @inject without @AndroidEntryPoint annotation, we will get the same error as using the reserved word &quot;lateinit&quot; and using it without assignment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/0*s_o8JdsaS0QzO7Is" /></figure><p>What if we want to implement an injection that needs another injection?</p><pre>interface MaskInterface2 {<br>}</pre><pre>class InjectionClass(maskInterface2: MaskInterface2) {<br>}</pre><pre>class InjectionClass2() : MaskInterface2</pre><p>It will do like this:</p><pre>class InjectionClass @Inject constructor(<br>  maskInterface2: MaskInterface2<br>) : MaskInterface {<br>}</pre><pre>@AndroidEntryPoint<br>class MainActivity : AppCompatActivity() {<br>  @Inject lateinit var mask: InjectionClass<br>  override fun onCreate(savedInstanceState: Bundle?) {<br>    WindowCompat.setDecorFitsSystemWindows(window, false)<br>    super.onCreate(savedInstanceState)<br>  }<br>}</pre><p>We can also add Context to the injection.</p><pre>class InjectionClass @Inject constructor(<br>  @ApplicationContext private val applicationContext: Context,<br>  @ActivityContext private val activityContext: Context,<br>  maskInterface2: MaskInterface2<br>)</pre><h4><strong>How to inject instances in Fragment?</strong></h4><p>Suppose we want to inject an object in Fragment. It&#39;s almost the same as Activity, we just use the same annotation @AndroidEntryPoint, and we can use the same provider we use to inject in Activity.</p><pre>@AndroidEntryPoint<br>class FirstFragment : Fragment() {<br>  @Inject<br>  lateinit var mask: MaskInterface<br>}</pre><h4><strong>How to inject viewModel in Activity or Fragment?</strong></h4><p>There is a little trick in this part. In MVVM Architecture. We usually need to inject some instance and use some method to let Activity, Fragment, or control flow use it.</p><p>Because ViewModel has a longer Lifecycle than Activity. So does have different ways to invoke it in Activity. We use ViewModelFactory to get ViewModel in Activity if we need. It will look like this.</p><pre>val viewModel: SampleViewModel by viewModels()</pre><p>Without the Hilt. We need to create a factory class to let the compiler know how to construct the ViewModel. It&#39;s boilerplate work. But with Hilt. We can use @HiltViewModel to let Hilt know how to construct the viewModel</p><pre>@HiltViewModel<br>class SampleViewModel<br>  @Inject constructor(): ViewModel() {<br>}</pre><p>Or we may have some injection used by the ViewModel:</p><pre>@HiltViewModel<br>class SampleViewModel @Inject constructor(<br>  @ApplicationContext private val applicationContext: Context,<br>  @ActivityContext private val activityContext: Context,<br>  maskInterface2: MaskInterface2<br>) : ViewModel() {<br>}</pre><p>Remember @Inject constructor is necessary even though you don&#39;t need any field. Hilt needs it to know how to construct the ViewModel. It needs to be marked.</p><p>That&#39;s all. You can use viewModels() to invoke ViewModel in Activity and Fragment.</p><p><strong>How to inject the Activity instance between Fragments?</strong></p><p>You might notice when we write a provider. We have @Module annotation, we have @Provides annotation, and we also have @InstallIn(ActivityComponent::class).</p><p>This annotation declares the lifecycle of the instance provider by annotated class. In this case, we can see ActivityComponet::class. That means the lifecycle of this instance provided by the annotated class is between Activity onCreate and onDestroy.</p><p>That also means we can use this provider with the same instance between two Fragments in the same Activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*FdYAeSqSss8py5VI" /></figure><p>Wait … What?</p><p>It&#39;s easy to make people so confused here. You annotate InstallIn(ActivityCompont::class) in a class doesn&#39;t mean the class provides the instance that lifecycle binds with Activity.</p><p>We still have one step to let the provider provide the instance lifecycle bind with Activity. We need to use @ActivityScoped.</p><pre>@Module<br>@InstallIn(ActivityComponent::class)<br>class ProviderModule {<br>  @ActivityScoped<br>  @Provides<br>  fun provide(): MaskInterface {<br>    return InjectionClass()<br>  }<br>}</pre><p>That means the instance provided by this method will live with the Activity.</p><p>So you can share the same instance between two Fragments owned by one Activity like this using @ActivityScoped</p><pre>@AndroidEntryPoint<br>class MainActivity : AppCompatActivity() {<br>  @Inject<br>  lateinit var mask: MaskInterface<br>}</pre><pre>@AndroidEntryPoint<br>class FirstFragment : Fragment() {<br>  @Inject<br>  lateinit var mask: MaskInterface<br>}</pre><pre>@AndroidEntryPoint<br>class SecondFragment : Fragment() {<br>  @Inject<br>  lateinit var mask: MaskInterface<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/0*2JU-aNiN9-WSbe-R" /></figure><p><strong>How is the injection instance lifecycle?</strong></p><p>Sometimes, we may want to provide an instance live with Fragment. Or maybe live with a ViewModel or even a View. Yap~ Hilt has supported this. I got some tables from the Android Developer&#39;s official document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bKZ3e6Gb14JXVtry" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o_0vzDilcQAbyXxM" /></figure><p>Those tables show how to use the lifecycle scope at Hilt. It&#39;s very obvious how to use the kind with @Singleton @ActivitySoped @ViewModelScoped @FragmentScoped.</p><p>But I wonder how to use @ViewScpoend</p><p>It&#39;s just like @FragmentScoped</p><pre>@Module<br>@InstallIn(ViewComponent::class)<br>class ProviderModule {<br>  @ViewScoped<br>  @Provides<br>  fun provide(): MaskInterface {<br>    return InjectionClass()<br>  }<br>}</pre><pre>@AndroidEntryPoint<br>class CustomView(context: Context, attrs: AttributeSet? = null) :<br>View(context, attrs) {<br>  @Inject<br>  lateinit var mask: MaskInterface<br>}</pre><p>It should work.</p><p>But I wonder when we should use it like this.</p><p>There is a scenario if the Fragment creates a view.</p><p>The Fragment would destroy the view frequently but not destroy itself, so we need to let the LiveData observer viewLifecycleOwner instead Fragment&#39;s lifecycle in some cases.</p><p>According to this thinking. We may have a scenario needing instance life bind with fragment view. It seems like the previous example.</p><p>Then why do we need @WithFragmentBindings? It seems viewScope already satisfies fragment view&#39;s lifecycle. But we may want to restrict view usage only on Fragment because it may design to align by Fragment. Using @WithFragmentBidnings means this injection object must always be attached through a fragment. Or it will throw an exception like this if we use this view but not inflate by Fragment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sN7Ry4fEbdmleN8M" /></figure><p><strong>How to inject different instances with the same interface.</strong></p><p>Sometimes, we may need to inject different instances with the same interface.</p><pre>class LocalInstance @Inject constructor(<br>) : MaskInterface<br><br>class RemoteInstance @Inject constructor() : MaskInterface@Module</pre><pre>@InstallIn(ActivityComponent::class)<br>class ProviderModule {<br>  @ActivityScoped<br>  @Provides<br>  fun provideLocal(): MaskInterface {<br>    return LocalInstance()<br>  }<br>  @ActivityScoped<br>  @Provides<br>  fun provideRemote(): MaskInterface {<br>    return RemoteInstance()<br>  }<br>}</pre><p>Then we got an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Z39Sv8OgN7PCcFf" /></figure><p>How should we split those two?</p><p>First, we need to add two annotation class</p><pre>@Qualifier<br>@Retention(AnnotationRetention.BINARY)<br>annotation class Local<br><br>@Qualifier<br>@Retention(AnnotationRetention.BINARY)<br>annotation class Remote</pre><p>Then we can use it to declare provided method:</p><pre>@Module<br>@InstallIn(ActivityComponent::class)<br>class ProviderModule {<br>  @ActivityScoped<br>  @Local<br>  @Provides<br>  fun provideLocal(): MaskInterface {<br>    return LocalInstance()<br>  }<br><br>  @ActivityScoped<br>  @Remote<br>  @Provides<br>  fun provideRemote(): MaskInterface {<br>    return RemoteInstance()<br>  }<br>}</pre><p>Then we should be able to inject the kind of instance that we want by those annotations</p><pre>@AndroidEntryPoint<br>class MainActivity : AppCompatActivity() {<br><br>  @Inject<br>  @Local<br>  lateinit var localInterface: MaskInterface<br><br>  @Inject<br>  @Remote<br>  lateinit var remoteInterface: MaskInterface<br>}</pre><h4>Summary</h4><p>Compare with Dagger. It seems like Hilt is a lot easier to use and understand than Dagger. Well, it&#39;s a good thing. Although It still makes people confuse when we see the error message from the compiler when we use something wrong or in some way wrong .</p><p>In my opinion. Koin is still my priority. But it’s still worth using Hilt when you have some dependency injection requirements.</p><h4>Reference</h4><p><a href="https://developer.android.com/training/dependency-injection/hilt-android">https://developer.android.com/training/dependency-injection/hilt-android</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=144851dacd59" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jastzeonic/something-about-the-hilt-144851dacd59">Something about The Hilt</a> was originally published in <a href="https://medium.com/jastzeonic">Jastzeonic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Myers Diff 那一兩件事情]]></title>
            <link>https://medium.com/jastzeonic/myers-diff-%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-5faf762f7350?source=rss-b868b6eecf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/5faf762f7350</guid>
            <dc:creator><![CDATA[Jast Lai]]></dc:creator>
            <pubDate>Sat, 24 Dec 2022 10:54:14 GMT</pubDate>
            <atom:updated>2022-12-24T10:54:14.563Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYfUNOZwtCcKPJkky-plaw.jpeg" /></figure><h3>前言</h3><p>說來好久沒寫文章了，寫著寫著成了季更了。</p><p>我想說維持良好傳統，在聖誕夜這篇發一篇怨念文，好茲以紀念我那連續幾年散不去的怨念，但是實在想不到主題，不過這幾天又提起來 DiffUtil 的東西，我赫然發現之前有提到關於 Myers Diff 這東西，我想想，那不然我就深入來檢視檢視這套演算法吧。</p><p>不免其俗的，放首歌來給這個聖誕夜打打祭(?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuflbS0zI5mo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuflbS0zI5mo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuflbS0zI5mo%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/bfd326bba90c2c041e5b67dad30f1c0d/href">https://medium.com/media/bfd326bba90c2c041e5b67dad30f1c0d/href</a></iframe><h3>說說那個 Diff</h3><p>說 Myers Diff 可能大家都不知道是啥，但是只要是寫程式的人，只要有用到 Git 不是用 Zip 去做版控，可能都會在不知不覺使用這玩意。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*INp4lxE9CicJQd5dHF_7jw.png" /></figure><p>Myers Diff 想要解決的問題很單純，就是拿兩個 Array，要把 Array1 變成Array2 。</p><p>最簡單最暴力的方法，當然是，把 Array1 全砍了，把 Array2 放上去，完美，不用燒腦。</p><p>但實務上這樣代價太大了。想像一下，你是古代一名抄書人，你抄了一本三國演義，然後發現你中間一行字把曹操寫成劉備了，不得了劉備成丞相了，這必須要修改，然後你必須要把你剛抄完的整版三國演義拋棄重抄，那代價有多大？</p><p>實務上，以上面那個抄書的例子，我們會希望可以把曹操那行字刪掉，新增劉備那行字。用這個簡單的例子我們可以知道，當我們把 array1 轉成 array2 時，我們會想要知道需要新增、刪除什麼？</p><p>這邊求簡單，我們把兩個 Array 用兩個 String 來表示，例如說我現在手上有 兩個字串</p><p>string a = &quot;abcdebef&quot;;</p><p>string b = &quot;acfdbef&quot;;</p><p>string a 要變成 string b 要新增甚麼字元，刪除甚麼字元。單純上面的問題還蠻簡單的，把 string a 丟進一個 map 裏頭計數，然後把 string b 逐個拿去問 map 做對應的 consumed ，就可以從剩下的 map 中得到需要刪除甚麼，剩餘的 string b 字串得到需要新增的字元。</p><p>我們會需要刪除 “be” ，新增 “f”。</p><p>但問題來了，上面那個作法，新增和移除是無序的，咋知道要刪掉哪個 b 和 e，新增的 f 又該放哪啊？有此可知，我們若將 string a 轉成 string b 我們會需要符合另外一個條件：</p><ul><li>我們需要知道新增和刪除的順序為何</li></ul><p>因此目標變成：</p><ul><li>找出步驟最少的新增和移除順序</li></ul><p>那這狀況就很有趣了，因為有可能會是先刪除幾個字元再新增幾個字元會比較省步數，也有可能是先新增幾個字元再刪除幾個字元比較省步數，也有可能是新增一個字元刪除一個字元再新增一個字元再刪除一個字元比較省步數。簡而言之，用線性的思維去這樣想，會得到一個一步一步試的暴力解才求得出答案的想法，至少我一開始是這樣想的。</p><p>這樣一步一步試某些時候步是不比 string a 砍掉後再把 string b 放上去來得省事嗎？</p><p>還真是，所以暴力解在乘載著先人的智慧的情況下不是最終解決辦法。</p><p>但總之，我們先把暴力解的順序用樹把它給畫下來：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hL2Y8fBrb0aVH6LZzsNuGA.png" /><figcaption>下面還會有很多排，我就不畫了</figcaption></figure><p>這個把樹，或者說圖(graph)實際畫下來也看不懂，那為了方便表示，我們把中間的省掉，只留下樹兩側的 node 再轉個方向，會變成這樣：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*BS6nnKvCpnToH93tAmJ2cw.png" /></figure><p>好我有點懶得寫 insert 和 remove 了，總之可以往右走是 remove，而往下走會是 insert，還有一個斜著走，意思是可以直接前往下一步，在這裡通常代表兩個字元一樣的時候。</p><p>為了方便表示，我把字元往上提一格，然後再它們底下標是一個步驟數</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*u863LMVq-krfdzZJ5HYR7w.png" /></figure><p>這些零代表甚麼都還沒做，就是個開始，那我們在來給第一步加上步驟次數，如果左邊對頂上的字元是一樣不用 +1，代表不需要異動，若是不一樣的，則需要 +1 ，代表要一次異動。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*W7c9StXSFJJVZ5z-j1Sj6w.png" /></figure><p>這應該不難理解， 當從字串 “abcdebef” 轉換的字串是【空】的時候，要刪除 a 需要 1 個步驟，當在刪除 a 後要刪除 b 則需要 2 個步驟，以此類推。在從【空】要轉成 “acfdbef”，要插入一個 a 需要 1 個步驟，在插入一個 a 之後插入 c ，需要 2 個步驟。</p><p>再來我們來到的是 string a 和 string b 的第一個字元，string a 的字元 &#39;a&#39; 的字元要怎麼變成 string b &#39;a&#39; 字元？很明顯， 字元 &#39;a&#39; 要變成字元 &#39;a&#39; 是不需要轉換的，是故可以走斜角，直接來到這，那也因為不用異動，所以步驟數是 +0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*p6aW8s0x1H4MiwNav_n2gA.png" /></figure><p>下一步，來到了 string a 的字元 b 和 string b 的字元 a，我們若要把 ab 轉換為 a ，則需要移除 b 一步，若要把 abc 轉換為 a ，則需要移除 bc 兩步，若要把 abcd 轉換為 a ，則需要移除 bcd 三步，以此類推。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*COmD8Hv0lErjxMuMKwj5dQ.png" /></figure><p>接著下一步。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*AtAdk-p3kkGP0p4kgmDHiQ.png" /></figure><p>到變成 ac 這一列，有趣的就來了。要從 a 變成 ac ，需要新增一個 c ，需要一步；那 ab 要變成 ac 只需要移除一個 b，然後新增一個 c ，需要兩步；那麼 abc 要變成 ac ，只需要移除一個 b ，ac 裡面已經有 c，則不需要新增 c，所以反而會比上一步 ab 變成 ac 少上一步。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*QOmJ-nbj_10lRXG_0_0t3g.png" /></figure><p>依照上面的邏輯，若從 abc 要變成 acf ，則在 c 對上 f 時，他可以是移除 b、c 後再加入 c、f 後來的，也可以是加入 cf 後再刪除 bc 來的。那我們要求的是最少步驟的，所以我們要取上一步最短的步驟，有 3 步的(增加 c 和 f 後移除 b)和 1 步(移除 b)的，再加上一步(增加 f 或移除 f)，3 大於 1 ，所以我們取 1 步，那我們需要 f ，所以會增加 f ，是故 abc 變成 acf 需要兩步(移除 b ，增加 f)。</p><p>我們若要從 abcdebef 變成 acf ，那會需要五個步驟，移除 b、d、e、b、e 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*kAXRbmzkegZxoR2zMzVP1A.png" /></figure><p>那把全部列出來 &quot;abcdebef&quot; 變成 &quot;acfdbef&quot; 需要三個步驟。移除 b、新增 f 、移除 e。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*sFc5E8l0GF3xAQLJsoN3BQ.png" /><figcaption>紅色代表刪除，綠色代表新增</figcaption></figure><p>恩，那這數字怎麼來的。有經驗的人可能已經知道了，沒錯就是那個聽了摀耳、見了喊打，大名鼎鼎的 dynamic programming 動態規劃，也就是 DP，</p><p>這邊的 DP 是在這步驟取當兩個字元相同，則直接走斜的(跳過刪除或新增)，而兩個字元不同時，看是新增(往下走來的)、或者是刪除(往右走來的)，兩者取較小的。</p><p>這樣看似解決了很大一部分的問題，但是有個問題是，這的時間複雜度為 O(m*n)，空間複雜度同樣為 O(m*n)，看起來還可以，但是提到 Big O 總是會想往 O(1) 靠近。那這是否還有可能再簡化呢？</p><h3>Myers Diff</h3><p>恩， 1986 年的時候，Eugene Wimberly“ Gene” Myers 發表了一篇論文，標題為：<a href="http://www.xmailserver.org/diff2.pdf">An O(ND) Difference Algorithm and Its Variations</a> ，講述了一個時間複雜度為 O(NlogN + D²) ，空間複雜度為 O(N) 的差分演算法，N 為兩個陣列數量相加的總和，D 為兩個陣列需要修改的最小值。這論文講述的東西即為後來俗稱的 Myers Diff。</p><p>Myers Diff 的核心概念是 K 線(不是股票那個)。意思是，以斜線傳過兩個陣列之間</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*Lhnb7rVXKh_RmkahuTUiDA.png" /><figcaption>K 軸</figcaption></figure><p>另外還有所謂的 Snake ，也就是兩個陣列在當前這個 X Y 座標上的內容是相同的(上圖灰階部分)，在這個情況下，座標 X Y 軸可以直接各加一跳過。</p><p>延續方才 string a = “abcdebef”、string b = “acfdbef” 的例子，我們先定義一個 x 和 y ，也就是起始位置。(0,0);</p><pre>int x = 0 , y = 0;</pre><p>我們把 a 和 b 展開 m = a.size() ，n = b.size()</p><pre>int m = a.size(), n = b.size();</pre><p>那這裡會需要一個 m+n * 2 -1 的整數陣列，用來儲存移動結果，那我這邊為了方便顯示，我用 map 來紀錄：</p><pre>map&lt;int,int&gt; v;</pre><p>若要以 x 為基準，則初始化 v[+1] = 0;，若要以 y 為基準，則初始化 v[-1] = 0;</p><p>這裡以初始化 x 為準。</p><pre>v[1] = 0;</pre><p>此外需要一個外層迴圈，從 0 開始，至 m+n(最差情況兩個字串完全不同)：</p><pre>for(int d=0 ; d&lt;=m+n ; d++)</pre><p>那這裡還會需要一個內層迴圈，用於表示 k 線，k 是從 -d 開始，那因為陣列的 index 無法用負數，所以我前面用 map 方便表示，用於儲存，一般文章表示通常會寫成 -d。</p><pre>for(int k = -d ; k &lt;= d ; k+=2)</pre><p>至於迴圈為什麼每次會跳 2 待會會提到。</p><p>那當 k == -d 時，意味在內層迴圈中已經刪到沒東西，只能 insert (向下走)，反之，當 k == + d 時，意味著已經加到沒東西可以加了，只能 delete(向右走)。</p><pre>//因為是以 x 為基準，所以只能 insert 時有 +1<br>//那沒東西可以加只能刪東西的時候，會動 Y ，所以不用 +1<br>if(k == -d){<br>  x = v[k+1];<br>else if(k == d){<br>  x = v[k-1]+1;<br>}</pre><p>那還有一個情況是，那如果 k != d 或 k!= -d 時呢？記得 v 裡頭儲存的會是 x 座標上一步是 insert (v[k-1])或是 delete(v[k+1]) 的 x 座標，你要不從左邊來，要不就從上面來的，有 Snake 的地方下面計算會跳過。這也是之所以為何上面那個迴圈 +2 的關係，因為前後兩步都是上一步做的事情，比過了無需再比較，那我們的目標是往座標的最終點走，所以兩者看誰比較大，就選他做下一步動作。</p><pre>if(v[k-1] &gt; v[k+1]){<br>  x = v[k-1] + 1;<br>}else{<br>  x = v[k+1];<br>}</pre><p>兩個判斷式合併一下會變成這樣</p><pre>if(k == -d || (k != d &amp;&amp; v[k-1] &lt; v[k+1])){<br>  x = v[k+1];<br>}else{<br>  x = v[k-1]+1;<br>}</pre><p>至於 y 我們可以利用 x 減掉 k 來計算出來</p><pre>y = x-k;</pre><p>那如果碰到 a[x] == b[y] 時，可以直接走 snake ，那可能會有連續的狀況，所以會用迴圈包起來，迴圈在跑可能會超過陣列長度，所以會加上長度判斷：</p><pre>while(x&lt;m &amp;&amp; y &lt; n &amp;&amp; a[x] == b[y]){<br>  x++;<br>  y++;<br>}</pre><p>最後要將走訪的 x 存入 v 中</p><pre>v[k] = x;</pre><p>那有可能在這一步就到達尾巴了，所以要有一個跳脫條件，當 x 和 y 真的走出了兩個陣列時，d 即為所需要的修改次數。</p><pre>if(x ≥ m &amp;&amp; y ≥ n){<br>  short_step = d;<br>  break;<br>}</pre><p>那最後程式碼長相會是這樣</p><pre>int x = 0 , y = 0;<br>int m = a.size(), n = b.size();<br>int sum = m+n;<br>map&lt;int,int&gt; v;<br>v[1] = 0;<br><br>int res = 0;<br>for(int d=0 ; d&lt;=sum ; d++){<br>  for(int k = -d ; k &lt;= d ; k+=2){<br>    if(k == -d || (k!= d &amp;&amp; v[k-1] &lt; v[k+1])){<br>      x = v[k+1];<br>    }else{<br>      x = v[k-1]+1;<br>    }<br><br>    y = x-k;<br><br>    while(x &lt; m &amp;&amp; y &lt; n &amp;&amp; a[x] == b[y]){<br>      x++;<br>      y++;<br>    }<br><br>    v[k] = x;<br>    if(x &gt;= m &amp;&amp; y &gt;= n){<br>      res = d;<br>      goto end;<br>    }<br>  }<br>}<br>end:</pre><p>好吧，寫到這，應該會滿滿的困惑。演算法和黑魔法基本上一個樣。</p><p>不過這邊可以看出來，推進 x 和 y 座標，主要靠的會是 snake，那若是沒有 snake ，則會依賴那個 +1 來跳脫迴圈，也就是說這個演算法的 worst case 會比用 DP 的 worst case 還要糟糕。</p><p>這情況還是挺常見的，但不是這裡要討論的東西。用 string a = “abcdebef”、string b = “acfdbef” 來跑會得到結果 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/1*dsQx2iJewuinBrVIzj-cOw.png" /></figure><p>當然陣列會大得多，不過這邊方便表示就寫這樣了。</p><p>而 d 會等於 3，代表 d 在算到第三次時，達到右下角底部，意思也就是上面那兩個字串需要三回修改。</p><p>只是這組陣列算什麼東西，我用它看不出修改的路徑為何？</p><p>有意思的地方是，我查閱大部分的資料，都從這一步開始有所分歧，畢竟每份實作的目的都不太一樣，分歧都是很合理的。但我覺得最有意思的地方是，大部分實作的演算法大概都是這形狀，包括 RecyclerView 的 DiffUtil</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*fKqkkA0wt0UMRTij6tvdFQ.png" /><figcaption>DiffUtil 裡的 Myers Diff</figcaption></figure><p>那我這邊的目標是把修改的路徑給印出來，只要有 (1,1) -&gt; (1,2) -&gt; (2,2)，便可以知道他具體是怎麼修改了。</p><p>我這邊先設計出一個結構，好方便我儲存 x 和 y 和他的上一個位置；</p><pre>struct Node {<br>  int x;<br>  int y;<br>  Node *pre;<br>  Node() :  pre(nullptr) {}<br>  Node(int x ,int y, Node *pre) : x(x),y(y), pre(pre) {}<br>};</pre><p>那按照剛才的邏輯，把 x 替換成 Node：</p><pre>map&lt;int,Node*&gt; v;<br>v[1] = new Node(0,-1,NULL);<br>//y -1 是一個很單純的輔助<br><br>Node *res = NULL;<br>for(int d=0 ; d&lt;=sum ; d++){<br>  for(int k = -d ; k &lt;= d ; k+=2){<br>    Node *pre = new Node();<br>    if(k == -d || (k!= d &amp;&amp; v[k-1]-&gt;x &lt; v[k+1]-&gt;x)){<br>      x  = v[k+1] -&gt; x;<br>      pre  = v[k+1];<br>    }else{<br>      x = v[k-1] -&gt; x +1;<br>      pre  = v[k-1];<br>    }<br><br>    y = x - k;<br>                <br>    Node *newNode = new Node(x,y,pre);<br><br>    while(x &lt; m &amp;&amp; y &lt; n &amp;&amp; a[x] == b[y]){<br>      x++;<br>      y++;<br>      // 這裡會 Snack 移動的點<br>      newNode = new Node(x,y,newNode);<br>    }<br>    if(x &gt; newNode -&gt; x){<br>      newNode = new Node(x,y,newNode);<br>    }<br><br>    v[k] = newNode;<br>    if(x &gt;= m &amp;&amp; y &gt;= n){<br>      res = v[k];<br>      goto end;<br>    }<br>  }<br>}<br>end:</pre><p>那這個會是一個 LinkedList ，這可以用一點技巧反轉，我這邊先不管空間複雜度用 stack 把它反過來就行：</p><pre>        stack&lt;Node*&gt; st;<br>        Node *cur = res;<br>        while(cur != NULL){<br>            st.push(cur);<br>            cur = cur-&gt;pre;<br>        }<br>        <br>        while(!st.empty()){<br>            cur = st.top();<br>            st.pop();<br>            cout &lt;&lt; &quot;(&quot; &lt;&lt; cur-&gt;x &lt;&lt;&quot;,&quot; &lt;&lt; cur -&gt;y  &lt;&lt; &quot;)&quot; &lt;&lt; &quot; -&gt; &quot;;<br>        }<br>        cout &lt;&lt; &quot;end&quot; &lt;&lt; &quot;\n&quot;;</pre><p>最終印出來的結果會是這樣：</p><blockquote>(0,-1) -&gt; (0,0) -&gt; (1,1) -&gt; (2,1) -&gt; (3,2) -&gt; (3,3) -&gt; (4,4) -&gt; (5,4) -&gt; (6,5) -&gt; (7,6) -&gt; (8,7) -&gt; end</blockquote><h3>結語</h3><p>It just works。</p><p>上面的算法可以看出來，最糟的情況，也就是字串 a 和字串 b 完全不一樣的時候，所需要的時間複雜度會遠比 DP 來得多。但是反過來說，如果需要修改的步驟接近 0 的話，所需要的時間複雜度就會比 DP 方法來的簡易多。</p><p>之前本想說大致上看懂這東西在幹嘛了，想說可以講解講解，但實際要我講解他具體在幹什麼，還是有很大的難度在，所以其實花了不少時間在研究和實驗。</p><p>上面的 Code 我原則上都直接在 LeetCode 上跑的，手賤就用 C++ 去寫了，寫起來倒是也很好玩，我沒搞錯在一些環境下直接複製貼上應該是跑不了的。</p><p>如果有任何問題，或是看到寫錯字，請不要吝嗇對我發問或對我糾正，您的回覆和迴響會是我寫文章最大的動力。</p><h3>參考資料</h3><p><a href="https://blog.robertelder.org/diff-algorithm/">Myers Diff Algorithm - Code &amp; Interactive Visualization</a></p><p><a href="https://blog.jcoglan.com/2017/02/17/the-myers-diff-algorithm-part-3/">https://blog.jcoglan.com/2017/02/17/the-myers-diff-algorithm-part-3/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5faf762f7350" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jastzeonic/myers-diff-%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-5faf762f7350">Myers Diff 那一兩件事情</a> was originally published in <a href="https://medium.com/jastzeonic">Jastzeonic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ktor Client 那一兩件事情]]></title>
            <link>https://medium.com/jastzeonic/ktor-client-%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-af9a06e6f070?source=rss-b868b6eecf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/af9a06e6f070</guid>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jast Lai]]></dc:creator>
            <pubDate>Tue, 30 Aug 2022 12:51:21 GMT</pubDate>
            <atom:updated>2022-08-30T12:51:21.156Z</atom:updated>
            <content:encoded><![CDATA[<p>使用 Kotlin 打網路的另一個選擇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*luF4t3kzlAqCRWlKwc_TNw.jpeg" /></figure><h3>前言</h3><p>我們看到 Ktor 通常都會想到：「喔，那個用 Kotlin 來寫後端的玩意」，不過實際上這玩意是可以用來在 Client 使用的。</p><p>某種程度上，如果使用到 KMM ，希望可以搞到跨平台，需要純 Kotlin 的程度的話，那麼使用 Ktor 就會是一個選擇。</p><p>不過我這邊不打算聊得這麼深就是了，我這篇文章只是很單純想要聊聊 Ktor 的 Client 怎麼使用。</p><p>以我的本業 Android 來說，我們使用 Retrofit 的現況，其實沒有什麼問題，在 Android 上頭，也算是目前的主流。不過說實話用久了會膩，而且還是有一些大大小小的問題，那是不是有什麼有趣的新選擇， Ktor 就是其中一個，那這就來看看著個東西怎麼用吧。</p><h3>設定</h3><p>我其實一直在想要不要為了寫這一篇文章來開個 KMM 專案， 不過我只打算用到 Client ，那想想好像直接用 Android 專案來講最為通俗，用起來可能對我的受眾也比較實際一點，那就還是用一個 Android 專案來說明好了。</p><p>原則上開好一個 Android 專案就行了，畢竟預設這些 Gradle 的設定都有了，大多時候只需要直接在 Gradle file 上加上</p><pre>implementation(“io.ktor:ktor-client-core:$ktor_version”)<br><em>implementation</em>(&quot;io.ktor:ktor-client-cio:$ktor_version&quot;)</pre><p>ktor_version 寫這篇文章的當下是 2.1.0，日後版本依該還會再往上長，有緣再修唄。</p><p>core 是必要的方法套件依賴(e.g. method Get、Post 那些)，而 CIO 則是 Ktor 的 engines 層，engines 是 Ktor 需要為了多平台而設計的抽象層，那 Kotlin 會根據你使用的平台去產出對應的東西，細節部分可以參照文件，這邊只要知道多平台需要用到它即可。</p><pre>val client = HttpClient(CIO) <strong>{<br>        </strong>expectSuccess = true<br>    <strong>}</strong></pre><p>使用上會類似這樣。那因為 Kotlin 幾乎是從 JVM 發根的，所以如果像是我使用 Android Project 的話，這裡可以把它省略掉。</p><pre>val client = HttpClient <strong>{<br>        </strong>expectSuccess = true<br>    <strong>}</strong></pre><h3>試著打一下</h3><p>那我只是想要試試看他能不能跑，我還沒有想讓他跑在手機上，那很簡單，開一個 kt file 寫上：</p><pre>fun main() {<br><br>    val client = HttpClient <strong>{<br>        </strong>expectSuccess = true<br>    <strong>}<br>    </strong><em>runBlocking </em><strong>{<br>        </strong>val response: HttpResponse = client.get(&quot;https://ktor.io/&quot;)<br>        <em>println</em>(response.status)<br>    <strong>}<br></strong>}</pre><p>把對應的 import 加上就可以了，直接執行應該就可以看到 200 了。</p><p>要注意的是 client.get 方法是 suspend function ，所以會需要在 coroutines scope 下使用，否則會無法編譯。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*Ex3NCl0RQ0MN7IeXM6jMmA.png" /><figcaption>看來沒什麼問題</figcaption></figure><p>不過上面這方法只列出了打完 API 的狀態，沒把結果列出來，那我要看我打 API 的 Response 呢？</p><p>改成這樣：</p><pre>fun main() {<br><br>    val client = <em>HttpClient </em><strong>{<br>        </strong>expectSuccess = true<br><br>    <strong>}<br>    </strong><em>runBlocking </em><strong>{<br>        </strong>val response: HttpResponse = client.get(&quot;https://ktor.io/&quot;)<br>        val responseString = response.body&lt;String&gt;()<br>        <em>println</em>(responseString)<br>    <strong>}<br></strong>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EddusCCg9m41bvdKy_-uog.png" /></figure><p>就可以把拿到的結果印出來了。</p><p>這樣達成了很簡單的 RESTful Get Response 的功能了。</p><h3>Request</h3><p>Ktor 的功能當然不僅止於 GET ，至少 Get 、Post 、Put、Delete 都得有嘛，當然 Ktor 都有提供這些功能。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*Q0mlsQR4IgHu5rAnb4c5ug.png" /></figure><p>這裡可以直接用 request 在裡面設定 method ，不過大多時候只要用 Ktor 提供的 extension 即可。</p><pre>val client = <em>HttpClient </em><strong>{<br>        </strong>expectSuccess = true<br><br>    <strong>}<br>    </strong><em>runBlocking </em><strong>{<br>        </strong>val responseGet: HttpResponse = client.get(&quot;https://ktor.io/&quot;) <strong><br>        </strong>val responsePost: HttpResponse = client.post(&quot;https://ktor.io/&quot;) <strong><br>        </strong>val responsePut: HttpResponse = client.put(&quot;https://ktor.io/&quot;)<strong><br>        </strong>val responseDelete: HttpResponse = client.delete(&quot;https://ktor.io/&quot;) <strong><br>        </strong>//....<br>    <strong>}</strong></pre><p>啊，當然我上面的方法打起來是都會失敗的，因為 Ktor.io 只能 GET (而且會拿到一整個 html )，想要試試看的話得去找能用的 url 。</p><h4>URL</h4><p>那其實可以注意到除了 request ，get 和 post 等等那些後面都還可以有個 lambda ，那個 lambda 的 receiver 是個 HttpRequestBuilder ，那顯然是可以用來做些設定的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*ttlZ12nu51EU6irYw9aOgg.png" /></figure><p>那這邊可以注意到的是 url 、 method 、 header 、body ，這幾個在打 RESTful 經常會異動到的 variable。</p><p>url 的部分我們可以注意到，他是 value ，看起來會不能動，使用上我們也確實不會直接動他，我們要修改的話要用 url {}</p><pre>val responseGet: HttpResponse = client.get(&quot;https://ktor.io/&quot;)<strong>{<br>    </strong>url <strong>{<br>        </strong><em>path</em>(&quot;docs/welcome.html&quot;)<br>    <strong>}<br>}</strong></pre><p>這裡可以注意到一件事情，就是我每回 get 都得把完整的 url 加上去，這樣打起來豈不是很麻煩，要切換 URL 也得開個全域搜尋。</p><p>在 Client 上可以設定一個 defaultRequest ，那就可以設定預設的 html 為何了。</p><pre>val client = <em>HttpClient </em><strong>{<br>    </strong><em>defaultRequest </em><strong>{<br>        </strong>url(https://medium.com/&quot;https://ktor.io/&quot;)<br>    <strong>}<br>    </strong>expectSuccess = true<br><br><strong>}<br></strong><em>runBlocking </em><strong>{<br>    </strong>val responseGet: HttpResponse = client.get <strong>{<br>        </strong>url <strong>{<br>            </strong><em>path</em>(&quot;docs/welcome.html&quot;)<br>        <strong>}<br>    }</strong></pre><pre><strong>//.....</strong></pre><pre><strong>}</strong></pre><p>或者寫成這樣</p><pre>val client = <em>HttpClient </em><strong>{<br>    </strong><em>defaultRequest </em><strong>{<br>        </strong>url(https://medium.com/&quot;https://ktor.io/&quot;)<br>    <strong>}<br>    </strong>expectSuccess = true<br><br><strong>}<br></strong><em>runBlocking </em><strong>{<br>    </strong>val responseGet: HttpResponse = client.get(&quot;docs/welcome.html&quot;)<br>    //....<br><strong>}</strong></pre><p>我們也常常會需要在 url 上加上 query 這時候也可以利用 url {} 裡面的 parameters 加上 query</p><pre>val responseGet: HttpResponse = client.get(&quot;docs/welcome.html&quot;) <strong>{<br>    </strong>url <strong>{<br>        </strong>parameters.append(&quot;name&quot;,&quot;value&quot;)<br>    <strong>}<br>}</strong></pre><p>method 可以改，也就是說可以在用 get 這個 extension 後把它改成 post ，雖然我強烈建議不要這麼做，沒必要做把紅燈變綠燈綠燈變黃燈這種事情。但是這確實是可行的。</p><h4>Header</h4><p>header 的部分就相對單純了，可以直接用 headers {} 就可以在一次 request 中加上 header 。</p><pre>val responseGet: HttpResponse = client.get(&quot;docs/welcome.html&quot;) <strong>{<br>    </strong><em>headers </em><strong>{<br>        </strong>append(HttpHeaders.Accept, &quot;text/html&quot;)<br>        append(HttpHeaders.Authorization, &quot;TOKEN&quot;)<br>        append(HttpHeaders.UserAgent, &quot;The right to play God.&quot;)<br>    <strong>}<br>}</strong></pre><p>那麼也不用 Header 跟 base url 一樣，每一次 request 都要設定也會頗麻煩，所以一樣也是可以在 client 上設定的。</p><pre>val client = <em>HttpClient </em><strong>{<br>    </strong><em>defaultRequest </em><strong>{<br>        </strong>url(https://medium.com/&quot;https://ktor.io/&quot;)<br>        <em>headers </em><strong>{<br>            </strong>append(HttpHeaders.Accept, &quot;text/html&quot;)<br>            append(HttpHeaders.Authorization, &quot;TOKEN&quot;)<br>            append(HttpHeaders.UserAgent, &quot;The right to play God.&quot;)<br>        <strong>}<br>    }<br>    </strong>expectSuccess = true<br><br><strong>}</strong></pre><h4>Body</h4><p>那來說說 body ，有取就有給嘛，只能 GET 的 Restful 工具不完整，若是要給的話，那用 Post 可以很容易達到，問題是要怎麼給 Body 呢？</p><pre>val response: HttpResponse = client.post(&quot;http://localhost:8080/post&quot;) <strong>{<br>    </strong><em>setBody</em>(&quot;Body content&quot;)<br><strong>}</strong></pre><p>這樣在後端就會收到這一串字的 byte code 了。</p><p>當然通俗一點的做法是需要使用到序列化的，把它轉成 Json 才能轉成比較方便。</p><pre>val response: HttpResponse = client.post(&quot;http://localhost:8080/post&quot;) <strong>{<br>    </strong><em>contentType</em>(ContentType.Application.Json)<br>    <em>setBody</em>(SomeData(&quot;&quot;, &quot;Jet&quot;))<br><strong>}</strong></pre><p>那這樣寫沒有問題，只是毫無意外的意外噴錯了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ze7Fa-DszYNpI_xGtP487w.png" /></figure><p>意思大概是在說，你想要序列化它，但是沒有告訴 Ktor 序列化的方法。</p><p>Ktor 是 Kotlin 的東西，也是 Jetbrain 本家的東西，所以使用 Ktor 的序列化工具，當然會比較推薦使用 serialization，這裡用 Ktor 的 serialization 就可以。</p><pre>implementation(“io.ktor:ktor-serialization-kotlinx-json:$ktor_version”)</pre><p>但是別忘記了 Ktor 是以跨平台為目的的東西，所以會需要使用一個叫做 ContentNegotiaion 的 plugin，作為抽象的介面。</p><pre>implementation(“io.ktor:ktor-client-content-negotiation:$ktor_version”)</pre><p>Kotlin serialization 因為會需要針對標記 @Serializable 的 class 產生 serialzer 所以會需要加一個 plugin 。</p><pre><em>kotlin</em>(&quot;plugin.serialization&quot;) <em>version </em>&quot;1.7.10&quot;</pre><p>加在專案上最外層的 gradle 應該就可以了。</p><pre><strong>@Serializable</strong><br>data class SomeData(val data: String, val data2: String)</pre><p>之後給 some data 加上 Serializable ，在 client 上設定 ContentNegotiation</p><pre>val client = <em>HttpClient </em><strong>{<br>    install(ContentNegotiation) {<br>        <em>json</em>()<br>    }<br>    </strong>expectSuccess = true<br><br><strong>}</strong></pre><p>那有用過 Serialization 的人應該就知道，在那個 Json 上可以設定一些 json 的東西。</p><pre>install(ContentNegotiation) <strong>{<br>    </strong><em>json</em>(<br>        <strong><em>Json </em>{<br>            prettyPrint = true<br>            isLenient = true<br>        }</strong>)<br><strong>}</strong></pre><p>這樣子</p><pre>val response: HttpResponse = client.post(&quot;http://localhost:8080/post&quot;) <strong>{<br>    </strong><em>contentType</em>(ContentType.Application.Json)<br>    <em>setBody</em>(SomeData(&quot;&quot;, &quot;Jet&quot;))<br><strong>}</strong></pre><p>後端就可以收到這串序列化後的資料了。</p><p>那麼像是要上傳檔案可以寫成這樣：</p><pre>val response2: HttpResponse = client.post(&quot;http://localhost:8080/upload&quot;) <strong>{<br>    </strong><em>setBody</em>(MultiPartFormDataContent(<br>        <em>formData </em><strong>{<br>            </strong>append(&quot;description&quot;, &quot;Ktor logo&quot;)<br>            append(&quot;image&quot;, File(&quot;ktor_logo.png&quot;).<em>readBytes</em>(), Headers.build <strong>{<br>                </strong>append(HttpHeaders.ContentType, &quot;image/png&quot;)<br>                append(HttpHeaders.ContentDisposition, &quot;filename=\&quot;ktor_logo.png\&quot;&quot;)<br>            <strong>}</strong>)<br>        <strong>}</strong>,<br>        boundary = &quot;WebAppBoundary&quot;<br>    )<br>    )<br>    <em>onUpload </em><strong>{ </strong>bytesSentTotal, contentLength <strong>-&gt;<br>        </strong><em>println</em>(&quot;Sent $bytesSentTotal bytes from $contentLength&quot;)<br>    <strong>}<br>}</strong></pre><p>或者是直接用 Ktor 提供的 extension</p><pre>val response: HttpResponse = client.<strong>submitFormWithBinaryData</strong>(<br>    url = &quot;http://localhost:8080/upload&quot;,<br>    formData = <em>formData </em><strong>{<br>        </strong>append(&quot;description&quot;, &quot;Ktor logo&quot;)<br>        append(&quot;image&quot;, File(&quot;ktor_logo.png&quot;).<em>readBytes</em>(), Headers.build <strong>{<br>            </strong>append(HttpHeaders.ContentType, &quot;image/png&quot;)<br>            append(HttpHeaders.ContentDisposition, &quot;filename=\&quot;ktor_logo.png\&quot;&quot;)<br>        <strong>}</strong>)<br>    <strong>}<br></strong>)</pre><p>不過我自己是比較喜歡前一個方法，因為這才有辦法拿到上傳進度。</p><h3>Response</h3><pre>val httpResponse: HttpResponse = client.get(&quot;https://ktor.io/&quot;)<br>val stringBody: String = httpResponse.body()</pre><p>剛有提到，直接用 Body 就可以取得很純粹的字串了，那可以注意到 Body 是需要推斷型別的，若是 assign 的地方沒有加上型別或者是沒有在 Body 上特別告訴他要轉成什麼型別會編譯不過。</p><p>這也就是說 body 能轉的型別不只是 string ，也可以轉成 ByteArray 或者是自定義過的反序列後型別。</p><pre>val httpResponse: HttpResponse = client.get(&quot;https://ktor.io/&quot;)<br>val byteArrayBody: ByteArray = httpResponse.body()</pre><p>那我們在剛在敘說 Request 的時候有提到 ContentNegotiation ，如果照剛剛上述的做法有成功把資料打上後端的話，那在這邊也可以很輕鬆的這樣接資料。</p><pre>val someData: SomeData = client.get(&quot;http://localhost:8080/get&quot;).body()</pre><p>那若是想要利用 Ktor 下載檔案的話，可以寫成這樣：</p><pre><em>runBlocking </em><strong>{<br>    </strong>client.prepareGet(&quot;https://ktor.io/&quot;).execute <strong>{ </strong>httpResponse <strong>-&gt;<br>        </strong>val channel: ByteReadChannel = httpResponse.body()<br>        while (!channel.isClosedForRead) {<br>            val packet = channel.readRemaining(<em>DEFAULT_BUFFER_SIZE</em>.toLong())<br>            while (!packet.isEmpty) {<br>                val bytes = packet.readBytes()<br>                file.<em>appendBytes</em>(bytes)<br>                <em>println</em>(&quot;Received ${file.length()} bytes from ${httpResponse.<em>contentLength</em>()}&quot;)<br>            }<br>        }<br>        <em>println</em>(&quot;A file saved to ${file.<em>path</em>}&quot;)<br>    <strong>}<br>}</strong></pre><h3>WebSocket</h3><p>Ktor client 還有一個蠻酷的東西，就是他可以直接用 web socket ，必要的話可以直接開一個 client 直接連上 ws。</p><p>不過連上 web socket 需要額外的套件，所以會需要 implementation 另外一個東西</p><pre><em>implementation</em>(&quot;io.ktor:ktor-client-websockets:$ktor_version&quot;)</pre><p>這樣在使用上應該就沒有問題了。</p><pre>val client = <em>HttpClient </em><strong>{<br>        </strong>install(WebSockets)<br>    <strong>}<br><br>    </strong><em>runBlocking </em><strong>{<br>        </strong>client.webSocket(method = HttpMethod.Get, host = &quot;127.0.0.1&quot;, port = 8899, path = &quot;/echo&quot;) <strong>{<br>            </strong>while (true) {<br>                val othersMessage = incoming.receive() as? Frame.Text ?: continue<br>                <em>println</em>(othersMessage.<em>readText</em>())<br>                val myMessage = <em>readLine</em>()<br>                if (myMessage != null) {<br>                    send(myMessage)<br>                }<br>            }<br>        <strong>}<br><br>    }<br><br>    </strong>client.close()</pre><p>那可以注意到的是，這邊 Client 建立 WebSocket 連線是使用 webSocket 這個 method，裡面會有一個 closure ，裡頭的 lambda 是會把 WebSocketSession 當成是 Context Receiver ，那你便可以使用者個 WebSocketSession send message 就是了。那裡頭還有提供一個 incoming ，他是一個 Channel ，可以利用他的 Received 等待訊息的接收這個 Websocket 連線所收到的訊息，這邊再搭配 Channel 就可以做出一個簡單 input output 的 websocket 了。</p><p>首先這邊要先等 incoming 來才能把我要送的訊息送出，此外我其實也沒有方法把訊息丟給 websocket 的 connection 。</p><p>最重要的是如果 incoming 是個 channel ，那他 receive 在那邊等，若是沒有訊息則他會在那邊等上一輩子，而偏偏這邊使用的又是 runBlocking ，client.close 可不會發訊息給 incoming 呦，也就是除非後端給你主動斷線，否則，這個連線是會等上一輩子的。</p><p>聽起來很浪漫對不對，不過浪漫似乎不是用在這邊。</p><p>要解決這個問題，那顯然會需要搭配一點東西，好在這個 closure 是一個 coroutines scope ，則有需要的話可以直接用 launch 開啟新的 coroutines。</p><pre>val sendChannel = <em>Channel</em>&lt;String&gt;()<br>val webSocketConnectionJob = someCoroutineScope.<em>launch </em><strong>{<br>    </strong>client.webSocket(method = HttpMethod.Get, host = &quot;127.0.0.1&quot;, port = 8899, path = &quot;/echo&quot;) <strong>{<br>        </strong><em>launch </em><strong>{<br>            </strong>for (message in incoming) {<br>                message as? Frame.Text ?: continue<br>                //Received message<br>                <em>println</em>(message)<br>            }<br>        <strong>}<br><br>        </strong><em>launch </em><strong>{<br>            </strong>while (true) {<br>                val message = sendChannel.receive()<br>                // Send new message<br>                send(message)<br>            }<br>        <strong>}<br>    }<br><br>}</strong></pre><p>那若是要關閉這個連線，則直接 cancel job 就可以了。</p><pre>webSocketConnectionJob.cancel()</pre><h3>結語</h3><p>赫然發現我花最多時間的是去釐清為什麼用 runBlocking 會讓 Websocket 關不掉連線。我本來以為我會花最多時間在用 Go 建立一個 WebSocket 的後端，但沒有想到搭配 html + JS 當 Client 交叉測試會這麼迅速。</p><p>Ktor 用起來我認為是很適合使用純 Kotlin 的人，特別是如果對 Kotlin 的 Coroutines 特別有愛的人，原則上用下去不可能不用 Coroutines。實際用起來也不是特別的困難，使用 Android 的人好像沒有特別的理由從 Retrofit 換去 Ktor (使用 Kotlin 可以應付 Retrofit 反射進去碰到 nullable 問題的話)，但是若是有需要使用 Websocket ，是可以考慮試試看。那更進一步的是，如果要使用 KMM ，需要顧忌跨平台層面的話，使用 Ktor 也會是一個選擇。</p><h3>參考資料</h3><p><a href="https://ktor.io/docs/getting-started-ktor-client.html">Creating a client application | Ktor</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af9a06e6f070" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jastzeonic/ktor-client-%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-af9a06e6f070">Ktor Client 那一兩件事情</a> was originally published in <a href="https://medium.com/jastzeonic">Jastzeonic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Leak 那一兩件事情]]></title>
            <link>https://medium.com/jastzeonic/memory-leak-%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-8f8d959fe8db?source=rss-b868b6eecf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f8d959fe8db</guid>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Jast Lai]]></dc:creator>
            <pubDate>Sun, 15 May 2022 13:04:03 GMT</pubDate>
            <atom:updated>2022-09-27T07:30:31.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ISL_TeTB0gk4M7bVeZL3zg.jpeg" /></figure><p>在我寫 Android 的職涯經歷中我經常碰到一件事情：</p><p>「你這東西不能傳進去裏頭當作 Local variable」</p><p>「這樣會造成 memory leak」</p><p>小時候我聽到一臉矇逼，前輩講講聽話就算了，但長大後，越想越不對勁，大家總說 memory leak ，那具體是甚麼意思？又是怎麼發生的？為什麼要避免呢？</p><h3>Memory Leak 的定義</h3><p>最近常常碰到一件事情，我常常講一個大家都知道的字眼、大家都懂的概念，但實際要我解釋這個字眼或者是這個概念的時候，就愣在那邊說不出半句話。</p><p>Memory leak 就是一個常見的例子，大家都知道是甚麼東西但大家都說不出來是甚麼東西，說大家可能有點誇張，但是說真的，知道這詞彙的意思但解釋不出來的人還真不少。</p><p>Memory leak 至少存在電腦科學當中一段時間了，有個叫做牛津語言(Oxford Languages)的地方給 Google Search 做了個定義</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*QSfmfKOKM9593nk1_gTzzA.png" /></figure><blockquote>A failure in a program to release discarded memory, causing impaired performance or failure.</blockquote><p>程式沒能成功釋放棄用的記憶體，造成效能的損失或是執行的失敗。</p><p>我自己是比較喜歡<a href="https://en.wikipedia.org/wiki/Memory_leak">維基百科</a>上的定義</p><blockquote>In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released.</blockquote><p>在電腦科學之中，記憶體洩漏是記憶體不再需要時未被釋放的不正確記憶體分配管理，是一種資源的流失。</p><p>每次看維基要翻譯成中文都覺得很困難。但這邊的詞彙提供了很重要的資訊，leak 是一個行為動作，我們可以想像，這個行為是一個容器有個破洞會漏東西出來，那 memory leak 漏的東西就是記憶體的空間，那容器是甚麼呢？這裡可以想像是 memory manager ，也就是說 memory manger 有流漏導致 memory 的洩漏浪費，故稱為 memory leak。</p><p>那必然會有某種程度的後果，這才會被稱為問題和錯誤嘛，那具體會發生甚麼事情呢？維基百科上是這樣說的：</p><blockquote>A memory leak reduces the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down vastly due to thrashing.</blockquote><p>Memory leak 會讓可用的記憶體變少導致電腦的效能變差。最終，最壞的狀況是，所有可用的記憶體都被占滿，導致系統或者裝置上所有的作業都沒法正常的運作，如應用程式失效、系統變慢或者是閃退等情況。</p><p>恩，這大家都知道，大家都覺得要避免的情況。</p><h3>那 Memory leak 怎麼發生的？</h3><p>要說這個，可以先從各種程式語言的老前輩 C 語言開始說起。</p><p>如果我們有寫過 C 應該就知道 C 的 standard library (stdlib.h)有個叫做 malloc 的 method ，字面意思上就可以看得出來他是用來分配記憶體的。</p><p>那如果在使用了 malloc ，程式執行完了，沒做啥其他的事情，就會 leak。那就是寫 C 時要有的習慣，寫完記得要 free()。</p><p>但問題是，人非聖賢，事無萬全。配置完記憶體用完後忘記釋放這種事情屢見不鮮 …</p><p>那麼是不是有這麼一套規則，可以 malloc 完，卻不用 free 便可以自行釋放記憶體的呢？</p><p>沒錯，這便是 Garbage Collection (GC)。</p><p>但是有 GC 具體做了甚麼事情，可以 malloc 後不需要 free 樣呢？</p><p>以 JVM 來說，一個 Application 會把需要配置 memory 的 object 放進一個 heap 當中進行管理，那麼當這個 object 不再被 Reference 到，那麼該物件就會被視為不被用到而被回收。</p><p>那具體是誰 Reference 到這個 object 呢？</p><p>這個情況大致上可以分成兩種，我認為概念上最好理解的應該就是 Reference count 了。</p><p>Reference count 的概念就是當一個 object 被 Reference 到，則 count 就會 +1，當 object 被 release ，則 count -1 ，當 count 等於 0 時，則物件立刻被釋放，Reference count 是顯而易見的，簡單，而且動作相當快，但缺點是碰到 Circular reference 則需要手動回收否則就會 memory leak 。當 A object Reference 到 B object ， B object Reference 到 A object 時，A B 兩個 count 都是 1，誰也不讓誰，結果就是若沒有手動回收，則會 memory leak。</p><p>那像是 Objective-C 、PHP 是以 Reference count 作為 GC 機制。</p><p>但回過頭來看， JVM ，或者說我最熟悉的 Android 的 Dalvikvm 這個方式嗎？</p><p>很顯然不是，前面有提到一點， Reference Count 應該不會太耗時間，反正碰到 object 的 Reference Count 為 0 時，就回收給你看，其他的我不管了。這樣所需的時間複雜度和空間複雜度應該都不多，這跟我們對 Java 或者是 Android 下達 GC 時，會很耗資源的印象不一樣。</p><p>咦?等等，這是在說，在 Android 上 circular reference 不會 memory leak 嗎?</p><p>恩，還真不會。</p><p>那肯定有個條件，有個條件是可以判斷該 object 是能被回收亦或是不能被回收的。</p><p>答案是 GC Roots 。</p><p>也就是說我們可以把 Object reference 關係想像成一棵樹(tree)，或者是一張圖(Graph)，是樹的話則會有一個根(root)，是圖的話則會有一個起始點 start point 。那麼只要該物件的關聯直接或間接連到那個根，則不能被回收。</p><p>所以要怎麼知道了，就是遍歷做標記啦。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-LAIUW5GmaDPN3ppcGVWA.png" /><figcaption>自 GC Roots 開始開始遍歷，標記所有有直接或間接被 GC Roots 參照到的 object</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6AAjWc8kK16RjbDpGe3rTQ.png" /><figcaption>遍歷完後把沒有被 GC Roots 參照到的 object 給釋放掉</figcaption></figure><p>簡單的概念。這也是最常見的 GC 方式，乃至於提到 GC 原則上都是泛指這種方法。</p><p>當然這個問題是顯而易見的。因為需要遍歷，這意味著，每次遍歷都至少需要 O(n) 的時間複雜度，那若是使用的 memory 越多， n 就越大，每次遍歷就會越久，則 GC 的代價越大。</p><p>那問題來了，那具體的 GC Roots 是甚麼？</p><p>可以參考 Eclipse 的<a href="https://help.eclipse.org/latest/index.jsp?topic=%2Forg.eclipse.mat.ui.help%2Fconcepts%2Fgcroots.html&amp;cp=37_2_3">文件</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHtl_Z-ibvUxEXrQl-CqgQ.png" /></figure><p>只是仔細看會發現，很多個好像都不常碰到。</p><p>要注意到，滿足被 GC 回收的條件是<strong>不被 </strong>GC Roots Reference 到，而不是沒 Reference 到 GC Roots。</p><p>細看在 GC Roots 的種類，真的要達到 memory leak 還真的不簡單，如果不是沒事把東西丟去給系統層 Reference ，那大多數情況都可以被 GC。</p><p>那我們最常看到的 Memory leak 例子是 Running Thread 也就是異步時，worker thread 與 main thread 的生命週期錯開。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*Fxh1FKa92puKckIAHSqAvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*PdUnBFCT6CZCDXmkkcmudA.png" /><figcaption>上面那個程式碼，跑了會碰到 NullPointerException</figcaption></figure><p>這我看到其實就很納悶了，異步執行導致狀態不如程式執行的預期，這問題不是叫做 Race condition 嗎？</p><p>所以我認為這比較偏向是 Race condition 的問題，比較不偏向是 memory leak。當然要說 thread 應該在 sample 被 assign 為 null 時就應該被釋放，但實際上卻沒被釋放，所以視為 memory leak 也是一個解釋。但如果這麼做是必要的話，解決問題的點應該是聚焦在 object 的狀態管理，而不是記憶體的釋放，因為這情況在多執行序的程式執行的程序當中每天都在發生。(當然不是說這樣寫就不用管記憶體，那還是得取決於你的記憶體怎麼用)。</p><p>我認為更符合 memory leak 條件的狀況應該是這樣：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*VhEjqR7CdMqWh8pjqt6KFA.png" /></figure><p>這個執行的情況比較尷尬的是，執行中的 Thread 毫無疑問是被 GC Roots Reference 的 (不然跑一半給回收這更尷尬了)，Thread 裏頭的 while 若是沒給任何中斷，則會無限 Run 下去，那麼尷尬的是因為這個 Thread Reference 到了 main 裏頭的 sample，導致 sample 的 instance 沒辦法被 GC ，明明他都已經 Run 完了，卻還是回收不掉，更過分的是這還會導致你的 Process 沒法被執行完成，積少成多，一塊銀用一粒汗來換，系統變慢了，最後終於把系統配給能用的記憶體給灌爆了，人人都恐懼的 Out of Memory 發生了。</p><p>這就很符合我一開始定義的條件了，這才是 memory leak 的起承轉合。這個尤其在跨層 IO 時很常發生，所以對外 IO 時要確定是否關閉，否則把自己的物件傳進去可能會被對方永遠留著。</p><h3>結語</h3><p>每次提到 memory leak 就好像提到佛地魔似的，大家都唯恐避之不及，一句話這樣會 memory leak ，所以就不這樣寫了。</p><p>我覺得最有意思的地方是，我在 Android 碰到大多被認定為 memory leak 的問題大多都跟異步有關，且到最後異步的執行序若是有執行完是都可以被回收的，而且產生敘述的問題也大多比較偏向是 Race condition。當然這可能跟 LeakCanary 或者是 AS 的工具判定有關，以 <a href="https://square.github.io/leakcanary/fundamentals-how-leakcanary-works/">LeakCanary </a>來說，他的判定條件是：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*NkQN4PsJUrsrif7RLN9Taw.png" /></figure><p>以 Activity 的來說，若 Activity 被 finish ，那他應該是要可以被被回收，但是因為他被 worker thread reference 到，間接給 GC Roots Reference 到，那便不能回收，那對 LeakCanary 來說，這東西便是 leak 了，畢竟這些工具不知道這個 Thread 何時會結束，也許等個五秒，但超過了，他就當作不合理應該被回收，於是判定是 leak，於是便有了這個訊息。</p><p>如果有任何問題，或是看到寫錯字，請不要吝嗇對我發問或對我糾正，您的回覆和迴響會是我寫文章最大的動力。</p><h3>參考資料</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_CruQY55HOk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_CruQY55HOk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_CruQY55HOk%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/58fa41aa129eb4d7e9ac5ab3c516c825/href">https://medium.com/media/58fa41aa129eb4d7e9ac5ab3c516c825/href</a></iframe><ul><li><a href="https://square.github.io/leakcanary/fundamentals-fixing-a-memory-leak/">Fixing a memory leak</a></li><li><a href="https://www.dynatrace.com/resources/ebooks/javabook/how-garbage-collection-works/">eBook: How Java Garbage Collection Works | Dynatrace</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f8d959fe8db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jastzeonic/memory-leak-%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-8f8d959fe8db">Memory Leak 那一兩件事情</a> was originally published in <a href="https://medium.com/jastzeonic">Jastzeonic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Context Receivers 的那一兩件事情]]></title>
            <link>https://medium.com/jastzeonic/kotlin-context-receivers-%E7%9A%84%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-ed065926f23f?source=rss-b868b6eecf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed065926f23f</guid>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jast Lai]]></dc:creator>
            <pubDate>Fri, 29 Apr 2022 14:00:04 GMT</pubDate>
            <atom:updated>2022-04-29T14:00:04.262Z</atom:updated>
            <content:encoded><![CDATA[<p>Context Receivers 是甚麼個玩意？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*tcBYahigNuIVJKxASuHrSg.jpeg" /></figure><h3>前言</h3><p>不知道各位有沒有遇過一種情況是這樣的，我這有兩個 interface 分別長這樣；</p><pre>interface A {<br>    val a: Int<br>}<br><br>interface B {<br>    val b: Int<br>}<br></pre><p>那使用上會是這樣</p><pre>fun method(a: A, b: B) {<br>    <em>println</em>(&quot;I want to combine this those parameter ${a.a} ${b.b}&quot;)<br>}</pre><p>覺得這樣要把所有的 parameter 帶進來有一點麻煩，理想上是寫這樣：</p><pre>fun method() {<br>    <em>println</em>(&quot;I want to combine this three parameter $a $b&quot;)<br>}</pre><p>但我要怎麼知道，a b c 三個項目是打哪來的呢？</p><p>這個時候我們可能會先想到 Extension</p><pre>fun A.method() {<br>    <em>println</em>(&quot;I want to combine this three parameter $a $b&quot;)<br>}</pre><p>但是這個 Extension 只是針對 A 的，我如果要把 B 的 b 傳進來，那我還是得傳入 B。</p><p>這裡我想到一個方法：</p><pre>interface A {<br>    val a: Int<br>}<br><br>interface B {<br>    val b: Int<br><strong>    fun A.method() {<br>        <em>println</em>(&quot;I want to combine this three parameter $a $b&quot;)<br>    }</strong><br>}</pre><p>在語法上的陳述是，我希望在有 B object 的情況下可以外掛 A 的 method。</p><p>只是實際寫要怎麼寫呢？</p><pre>fun main() {<br>    val a: A = AImpl()<br>    val b: B = BImpl()<br>    b ... // How should I write this ?<br>    a.method()<br>}</pre><p>Kotlin 在這裡提供一個 inline function 叫做 with</p><pre>fun main() {<br>    val a: A = AImpl()<br>    val b: B = BImpl()<br><strong>    <em>with</em>(b) {<br>        a.<em>method</em>()<br>    }<br></strong>}</pre><p>這樣就可以做到在限定在某個 object 底下使用某個 Extension 。</p><p>只是我這樣寫的時候被我同事看到，他露出了困惑的表情，然後問：「你這是在寫三小？」</p><p>況且，如果我們今天面對的是這種情況：</p><pre>interface A {<br>    val a: Int<br>}<br><br>interface B {<br>    val b: Int<br>}<br><br>interface C {<br>    val c: Int<br>}<br><br>fun method(a: A, b: B, c: C) {<br>    <em>println</em>(&quot;I want to combine this three parameter ${a.a} ${b.b} ${c.c}&quot;)<br>}</pre><p>那像是這情況，就算在 interface 掛上 A 的 extension ，但你一樣也是得面對 要傳入 C instance 的問題。</p><h3>什麼是 Receiver ?</h3><p>若要了解 Context Receivers 為何物，勢必要先了解在 Kotlin 裡頭的 Receiver 為何物?</p><p>恩，照理說如果有寫 Kotlin ，而且還寫上一段時間，應該有很大的機率看過，或者是使用過 Receiver 了，當然我們最常見的 case ，就是在使用 Extension 或者是 lambda 了，這裡用 Extension 舉個例子：</p><pre>fun main(){<br>    &quot;This is a String.&quot;.<em>extensionFun</em>()<br>}<br><br>private fun String.extensionFun() {<br>    <em>println</em>(this)<br>}</pre><p>Emm … 有意思的地方是，誰是 receiver ，具體又 receive 了甚麼東西呢？</p><p>這一部分其實可以在 kotlin source code 裏頭一看究竟，用我們剛才用到的 with function 來看。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*TIXdvMPE5jdIShUPtTLo_Q.png" /></figure><p>我們可以看到 with 傳入的東西叫做 receiver ，也就是說如果我把上面的 Code 改成這樣：</p><pre>fun main() {<br><strong>    <em>with</em>(&quot;This is a String.&quot;) {<br>        <em>extensionFun</em>()<br>    }<br></strong>}<br><br>private fun String.extensionFun() {<br>    <em>println</em>(this)<br>}</pre><p>那可以看到 &quot;This is a String&quot; 這個 String 就是 receiver ，而他 receive 了那個 block。</p><p>換句話說，可以把上頭的 extensionFun 解釋為：要讓一個 String 作為 Receiver 去接收名為 extension 的這個 Block。</p><p>這樣的好處就是可以在寫 Code 時可以不用這麼專注在整體的結構上頭。</p><h3>那麼 Context Receivers 又是啥？</h3><p>知道 Receiver 是甚麼玩意之後，那 context receivers 解釋起來就不難了， receivers 是 receiver 的複數， context 我們可以解釋成是帶有某些條件的意境(在語言上就是語境，也就是上下文，context 這個在中文真的很難翻到位)，也就是說 Kotlin 的 Context Receivers 就是指某個 object 或 method 帶有一個多個 Receiver 的屬性。</p><h3>別廢話讓我看 Code</h3><p>Context Receiver 在 Jetbrains 目前的實作上仍定調為實驗階段，所以官方目前的推薦是在可以隨便玩玩的 Project 上嘗試就好(雖然我自己在寫 Compose 的時候會有點想用他)，目前也只能在 JVM 上頭被編譯，而且也不是預設開啟，所以如果說要玩，那麼就需要改一下 Gradle 的設定：</p><p>KTS：</p><pre>tasks.withType&lt;KotlinCompile&gt;{<br>  kotlinOptions.jvmTarget = &quot;1.8&quot;<br>  <strong>kotlinOptions.freeCompilerArgs = listOf(&quot;-Xcontext-receivers&quot;)</strong></pre><pre>}</pre><p>Groovy：</p><pre>kotlinOptions <strong>{<br>    </strong>jvmTarget = &#39;1.8&#39;<br><strong>    freeCompilerArgs = [&quot;-Xcontext-receivers&quot;]</strong><br><strong>}</strong></pre><p>不設定你會看到 IDE 凶巴巴的跟你說：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*zccH863XJBAyB7-3fOTcQA.png" /></figure><p>編譯不會過就算惹，IDE 也根本不知道你想幹嘛就是了。</p><p>好，那麼就來舉個例子吧：</p><pre>fun addMonthAndPrintFormattedDate(calendar: Calendar, sdf: SimpleDateFormat) {<br>    calendar.add(Calendar.<em>MONTH</em>, 1)<br>    <em>println</em>(sdf.format(calendar.time))<br>}</pre><p>這個方法很簡單，我們給 calendar 加上一個月，然後印出來。</p><p>那實作上會是這樣：</p><pre>fun main() {<br>    val calendar = Calendar.getInstance()<br>    val sdf = SimpleDateFormat(&quot;yyyy/MM/dd&quot;, Locale.getDefault())<br><br>    addMonthAndPrintFormattedDate(calendar, sdf)<br>    addMonthAndPrintFormattedDate(calendar, sdf)<br>    addMonthAndPrintFormattedDate(calendar, sdf)<br>}</pre><p>那個 sdf 每次用每次都得傳入還是有點擾人，我們在傳統的方式上可能會採用把這玩意包成一個 class 的做法，或者是用 Extension 的方式。 extension 的方法就回到這篇文章一開始的問題上了。</p><p>那寫法可以改成這樣：</p><pre>fun SimpleDateFormat.addMonthAndPrintFormattedDate(calendar: Calendar) {<br>    calendar.add(Calendar.<em>MONTH</em>, 1)</pre><pre><em>    println</em>(format(calendar.time))<br>}</pre><p>最後會變成這樣：</p><pre>fun main() {<br>    val calendar = Calendar.getInstance()<br>    val sdf = SimpleDateFormat(&quot;yyyy/MM/dd&quot;, Locale.getDefault())<br><br>    <em>with</em>(sdf) <strong>{<br>        </strong>addAMonthAndPrintFormattedDate(calendar)<br>        addAMonthAndPrintFormattedDate(calendar)<br>        addAMonthAndPrintFormattedDate(calendar)<br>    <strong>}<br></strong>}</pre><p>只是有個問題是，如果仔細端看 SimpleDateFormat 的 Extension addMonthAndPrintFormattedDate 會發現，在 Calendar 上加入一個月這件事情是由 SimpleDateFormat 來做了，這樣在語境上相當的不合邏輯：「簡易日期格式工具給 Calendar 加了一個月上去並印出規格化後的日期」，日期格式工具怎麼會負責修改 Calendar 呢？</p><blockquote><em>在我理解到我一個月後回來看到這段會不知道當時的我在 do 三小的時候，我默默地說了一句：「加個註解好惹」</em></blockquote><p>而且每次都要傳入 calendar 也有點煩。</p><p>這也便是 Context Receivers 想要達成的目的之一：當你需要類似 SimpleDataFormat 的屬性作為 Context 的同時，省去上面攏長的變數和定義。</p><p>那其實要改也不難，就是類似這樣：</p><pre><strong>context(SimpleDateFormat)</strong><br>fun addMonthAndPrintFormattedDate(calendar: Calendar) {<br>    calendar.add(Calendar.<em>MONTH</em>, 1)<br>    <strong><em>println</em>(format(calendar.<em>time</em>))</strong><br>}</pre><p>那實際的 control flow 也不需要變動，按照原樣就好，或者可以改成用 run：</p><pre>fun main() {<br>    val calendar = Calendar.getInstance()<br>    val sdf = SimpleDateFormat(&quot;yyyy/MM/dd&quot;, Locale.getDefault())<br><br>    sdf.<em>run </em><strong>{  <br>        </strong>addMonthAndPrintFormattedDate(calendar)<br>        addMonthAndPrintFormattedDate(calendar)<br>        addMonthAndPrintFormattedDate(calendar)<br>    <strong>}<br></strong>}</pre><p>那更進一步，可以把 calender 也給加上去 context 上頭：</p><pre><strong>context(SimpleDateFormat, Calendar)</strong><br>fun addMonthAndPrintFormattedDate() {<br><strong>    add(Calendar.<em>MONTH</em>, 1)<br>    <em>println</em>(format(<em>time</em>))</strong><br>}</pre><p>control flow 則會變成這樣：</p><pre>fun main() {<br>    val calendar = Calendar.getInstance()<br>    val sdf = SimpleDateFormat(&quot;yyyy/MM/dd&quot;, Locale.getDefault())<br><br>    with(sdf) <strong>{<br>        </strong>with(calendar) <strong>{<br>            </strong>addMonthAndPrintFormattedDate()<br>            addMonthAndPrintFormattedDate()<br>            addMonthAndPrintFormattedDate()<br>        <strong>}<br>    }<br></strong>}</pre><p>當然要注意到， Kotlin 畢竟也只是一碼程式語言，他還沒本事推斷出具體要使用甚麼實體，所以使用上沒加 with 或者是 run 或者是 apply 之類定義 receiver 的 method 會辨識不出來。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*sqLgbgY2RnL3CNxAbmqjTw.png" /></figure><blockquote><em>是說這樣的 with 和 with 會有波動拳的情況，只是在 Jetbrains 的影片有提到，未來會有更優雅的寫法。</em></blockquote><h3>Multiple Receivers</h3><p>那有了上面的例子，我們應該可以很清楚地回答我一開始提到的問題了，當我有 A B C 三個 interface 的時候，我有沒有比較省事的寫法呢？</p><pre>interface A {<br>    val a: Int<br>}<br><br>interface B {<br>    val b: Int<br>}<br><br>interface C {<br>    val c: Int<br>}<br><br>context(A, B, C)<br>fun method() {<br>    <em>println</em>(&quot;I want to combine this three parameter $a $b $c&quot;)<br>}</pre><p>實際寫起來要讓他 work 會長成這樣</p><pre>interface A {<br>    val a: Int<br>}<br><br>interface B {<br>    val b: Int<br>}<br><br>interface C {<br>    val c: Int<br>}<br><br>class AImpl : A {<br>    override val a: Int = 0<br>}<br><br>class BImpl : B {<br>    override val b: Int = 0<br>}<br><br>class CImpl : C {<br>    override val c: Int = 0<br>}<br><br><br>context(A, B, C)<br>fun method() {<br>    <em>println</em>(&quot;I want to combine this three parameter $a $b $c&quot;)<br>}<br><br><br><br>fun main(){<br>    val a:A = AImpl()<br>    val b:B = BImpl()<br>    val c:C = CImpl()<br>    with(a)<strong>{<br>        </strong>with(b)<strong>{<br>            </strong>with(c)<strong>{<br>                </strong><em>method</em>()<br>            <strong>}<br>        }<br>    }<br></strong>}</pre><p>yep ~就是這樣。</p><p>只是在寫的過程中，應該就會發現到這會有一點問題了，上述的情況是在參數和方法名稱都不一樣的時候，那如果說我 interface A 有個 methodA ，而我 interface B也有個 methodA 時，這該怎麼辦呢？</p><pre>interface A {<br>    val a: Int<br>    fun method1()<br>}<br><br>interface B {<br>    val b: Int<br>    fun method1()<br>}</pre><pre>context(A, B, C)<br>fun method() {<br>    <em>println</em>(&quot;I want to combine this three parameter $a $b $c&quot;)<br>    method1()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*rthA8sRMB_uNrgVG75-t_w.png" /></figure><p>其實情況跟在用巢狀的 run 中的 this 一樣，解決的方法也是一樣的 — 用 labeled</p><pre>context(A, B, C)<br>fun method() {<br>    <em>println</em>(&quot;I want to combine this three parameter $a $b $c&quot;)<br><strong>    this@A.method1()<br>    this@B.method1()</strong><br>}</pre><p>只是這樣就很有趣了，當你有大量會有 overload resolution ambiguity 的 method 或 parameter 在 context receivers 中時，你會需要標註大量的 labeled 了，這樣好像沒省事到哪去。</p><p>但事實上會有這種情況，就不合乎 context receivers 的精神了， Context Receivers 的精神是，在該物件底下的 field 的都可以明確被辨別時，才會用這個方法去節省讀寫標記這些物件的力氣，如果有大量需要標記 labeled 的物件，那使用 Context Receivers 就不是那麼的合適了。</p><p>當然也有很多方法可以轉圜，只是適合與否得由撰寫者自己決定了，例如官方影片提到的包一層 interface ，或者是乾脆另外寫一個 method ，像是這樣：</p><pre>context(A, B, C)<br>fun method() {<br>    <em>println</em>(&quot;I want to combine this three parameter $a $b $c&quot;)<br>    <em>methodForA</em>()<br>    <em>methodForB</em>()<br><br>}<br><br><strong>context(A)<br>fun methodForA(){<br>    method1()<br>}</strong></pre><pre><strong>context(B)<br>fun methodForB(){<br>    method1()<br>}</strong></pre><p>都是一個轉圜的方式，就看怎麼樣去做取捨了。</p><h3><strong>Context Receivers 和 Extension 的差別</strong></h3><p>問題是在， Context Receivers 和 Extension 實作上的差別好像就在 Receiver 的數量，當 Receiver 都只有一個的時候，引擎蓋底下的實作方法甚至相同。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*dJ02cwd5dc1MNPW5DjrG3A.png" /><figcaption>名稱相同還會吃 Kotlin 拐子</figcaption></figure><p>但是在語境上，卻有 in 跟 on 的區別，意思是，在 Extensions 語意上，你是<strong>在這個 object 上</strong>呼叫這個 method ；在 Context Receivers 語意上，你是<strong>在有這個 object 時</strong>呼叫這個 method。</p><p>所以不會看到 Context Receivers 被這樣寫：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*yMIlaxZj0Duha_R1MpPKLg.png" /></figure><h3>不只 function</h3><p>如果必要的話，也是可以把 Context Receivers 放進去 class 裏頭的：</p><pre>class SimpleClass{<br>    context(A, B, C)<br>    fun method() {<br>        <em>println</em>(&quot;I want to combine this three parameter $a $b $c&quot;)<br>    }<br>}<br><br>fun main() {<br>    val a: A = AImpl()<br>    val b: B = BImpl()<br>    val c: C = CImpl()<br>    val simpleClass = SimpleClass()<br>    with(a) <strong>{<br>        </strong>with(b) <strong>{<br>            </strong>with(c) <strong>{<br>                </strong>sample.method()<br>            <strong>}<br>        }<br>    }<br></strong>}</pre><p>當然，如果必要的話，也是可以把 Context Receivers 放到 class 上頭：</p><pre>context(A, B, C)<br>class SimpleClass {<br>    fun method() {<br>        <em>println</em>(&quot;I want to combine this three parameter $a $b $c&quot;)<br>    }<br>}<br><br>fun main() {<br>    val a: A = AImpl()<br>    val b: B = BImpl()<br>    val c: C = CImpl()<br>    val simpleClass = with(a) <strong>{<br>        </strong>with(b) <strong>{<br>            </strong>with(c) <strong>{<br>                </strong>SimpleClass()<br>            <strong>}<br>        }<br>    }<br>    </strong>simpleClass.method()<br>}</pre><h3>結語</h3><p>總而言之，我認為 Context Receivers 主要的目標是要區別 Extension 在使用上會有「讓醬油去做飯」這種語法謬誤的情況，若是他在語境上會更接近「在有醬油的情況做飯」。</p><p>此外我認為 Context Receivers 也可以解決一些寫語法很攏的問題，就像我們寫 Android 在定義一些 View 的 attribution 時，可能會使用語法糖 apply 或者 run 之類的方法，來省去讀寫一大堆東西的功夫。</p><p>雖然這玩意目前還在實驗階段，但還挺讓人期待他未來會怎麼樣被應用的就是了。</p><p>如果有任何問題，或是看到寫錯字，請不要吝嗇對我發問或對我糾正，您的回覆和迴響會是我寫文章最大的動力。</p><h3>參考資料</h3><p><a href="https://github.com/Kotlin/KEEP/blob/master/proposals/context-receivers.md">https://github.com/Kotlin/KEEP/blob/master/proposals/context-receivers.md</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGISPalIVdQY%3Fstart%3D227%26feature%3Doembed%26start%3D227&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGISPalIVdQY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGISPalIVdQY%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/b14c4ae4773ae9ea52262b719eb78276/href">https://medium.com/media/b14c4ae4773ae9ea52262b719eb78276/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed065926f23f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jastzeonic/kotlin-context-receivers-%E7%9A%84%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-ed065926f23f">Kotlin Context Receivers 的那一兩件事情</a> was originally published in <a href="https://medium.com/jastzeonic">Jastzeonic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose Layout 層級會有 Double taxation 嗎？那一兩件事情]]></title>
            <link>https://medium.com/jastzeonic/jetpack-compose-layout-%E5%B1%A4%E7%B4%9A%E6%9C%83%E6%9C%89-double-taxation-%E5%97%8E-%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-3691580e828c?source=rss-b868b6eecf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/3691580e828c</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jast Lai]]></dc:creator>
            <pubDate>Sat, 25 Dec 2021 11:06:55 GMT</pubDate>
            <atom:updated>2021-12-26T07:46:30.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IeOjP5IXdv5KNCvKS_N_gQ.jpeg" /></figure><p>聖誕節嘛，按照慣例，先來放首歌吧。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F16y1AkoZkmQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D16y1AkoZkmQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F16y1AkoZkmQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d5dad618160f5b963a663a56edf53c7/href">https://medium.com/media/9d5dad618160f5b963a663a56edf53c7/href</a></iframe><p>不知道為啥，我很想放這首歌，聽著聽著就上癮了，總而言之，該死的聖誕節。</p><h3>前言</h3><p>大約半年前我曾好奇提問過，使用 LinearLayout 的 weight 會有 performance 的問題，那使用 Jetpack Compose 的 weight 就不會有類似的問題嗎？因為 Compose 的 Layout 看需要甚至得疊上更多層呢？這樣狀況不會更嚴重嗎？</p><p>以這些問題做為起點，開始迷迷網網地進行調查。</p><h3>Double taxation</h3><p>解答第一個問題，那我們理所當然地要回頭看一下使用 LinearLayout 的 weight 會有 performance 的問題。這還蠻妙的，我們會知道這個問題，大多時候不是在 Layout 的時候跟你吐了甚麼例外事件，而是在我們實作 xml 的時候會跳一個 lint warning：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*nJ2ibdXLjiz-dzRizysIFw.png" /></figure><p>網路上查大多數的資料都告訴我們怎麼解決掉這個問題，而不是這個問題怎麼發生的，這不禁讓我好奇了起來。</p><p>layout weight 顯然跟 View 的 onMeasure 有關，那麼顯然的 LinearLayout 是個 Viewgroup ，那除了 measure 自己外，更多的是 measure 自己的 Child 。那我們可已透過自訂一個 View ，來看 LinearLayout measure 自己 Child 的次數。</p><pre>class LogView(context: Context, attrs: AttributeSet?) : View(context, attrs) {<br><br>    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {<br>        super.onMeasure(widthMeasureSpec, heightMeasureSpec)<br>        Log.v(&quot;Jast at here server&quot;, &quot;onMeasure : $<em>tag</em>&quot;)<br>    }<br>}</pre><p>XML：</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:tag=&quot;root&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;com.example.playground.LogView<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:tag=&quot;rootChild1&quot;/&gt;<br></pre><pre>&lt;/LinearLayout&gt;</pre><p>那實際跑起來我們可以看到結果：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*ur5eY_xwRqXycNOX8KPcCQ.png" /></figure><p>在一個 LinearLayout 下，若是沒有設定 layout weight 的話，需要被 measure 兩次，咦？為什麼要兩次呢？</p><p>雖說 LinearLayout 的特性是根據你設定的 orientation ，排列底下的 Children 的，但是因為 root layout 會需要先算過 Layout Hierarchy 的 measure 後再 measure 一次，所以會 measure 兩次。這一部分我目前還沒法解釋出為何，但這部分不影響 weight 的解讀。</p><p>在沒有 Layout weight 的情況下，就算疊到五層六層七層，對 LogView 來說，他只會被 measure 兩次。</p><p>那麼我們在 xml 加上了 layout_weight 呢？</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:tag=&quot;root&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;com.example.playground.LogView<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;match_parent&quot;<br><strong>        android:layout_weight=&quot;1&quot;</strong><br>        android:tag=&quot;rootChild1&quot;/&gt;<br><br><br>&lt;/LinearLayout&gt;</pre><p>結果會是這樣：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*_f9nYYboQqglfNKtWLM6AQ.png" /></figure><p>可以發現被 measure 的次數 X2 了。</p><p>這原因主要是因為 Child 的 Layout weigh 還有寬或高等資料需要在第一次 measure 後才會得到(e.g. 最大 child 的寬或高)，那以 LinearLayout 的邏輯來說，需要這些資訊才能去計算 layout weight 代表的寬高(例如所有 children 的 layout_weight 為 1 ，那找出最大的那一個 child 來讓所有 children 都一樣大小)，所以會比原先的 measure 多一次。<strong>Layout 在無法一次測量獲得完整資訊，而需要進行一次以上的測量，這個行為現象被稱為 Double taxation。</strong></p><p>那 View Tree 的走訪遞迴特性，每層 LinearLayout 都需要對自己的 Child 進行兩次 measure 。是故以這個 case 從最初的 2 次開始加上 weight 會被 x2 ，每增加一層，就會再多 x2，意思是，假如我再多一層 LinearLayout ，那麼 measure 的次數會變成 2³</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:tag=&quot;root&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:layout_weight=&quot;1&quot;&gt;<br><br>        &lt;com.example.playground.LogView<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;match_parent&quot;<br>            android:layout_weight=&quot;1&quot;<br>            android:tag=&quot;rootChild1&quot; /&gt;<br><br>    &lt;/LinearLayout&gt;<br><br>&lt;/LinearLayout&gt;</pre><p>結果會是這樣：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*73JMC_dVz_vWEn3XQwbWZA.png" /></figure><p>對 child view 來說，假如每一層都有 layout weight ，則它位於第 n 層，measure 次數則為 2^n，時間複雜度為 O(2^n)，這通常是演算法暴力破解法的時間複雜度，是故可以當作 bad performance 。</p><p>當然若是加上其他的 child ，那次數就會更恐怖了，以這個例子來說：</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:tag=&quot;root&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:layout_weight=&quot;1&quot;&gt;<br><br>        &lt;com.example.playground.LogView<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;match_parent&quot;<br>            android:layout_weight=&quot;1&quot;<br>            android:tag=&quot;rootChild1&quot; /&gt;<br><br>        &lt;com.example.playground.LogView<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;match_parent&quot;<br>            android:layout_weight=&quot;1&quot;<br>            android:tag=&quot;rootChild1&quot; /&gt;<br><br>        &lt;com.example.playground.LogView<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;match_parent&quot;<br>            android:layout_weight=&quot;1&quot;<br>            android:tag=&quot;rootChild1&quot; /&gt;<br><br><br>    &lt;/LinearLayout&gt;<br><br>&lt;/LinearLayout&gt;</pre><p>measure 的次數會是 24 次，意思是 3 x 2³</p><p>那像是我們過往會有的需求，九宮格，類似 orientation vertical 包三個 LinearLayout horizontal 裏頭有三個 View 的那種，則會變成 3x3x2³ = 72 。九個 view 就需要 measure 72 次，這個 C/P 值暴低的阿。</p><h3>Jetpack Compose 的層級</h3><p>在寫 Android 的時候，我們總會說要盡量減低層級，LinearLayout 的情況固然是一個例子，但是請務必把它當成特例：在使用 LinearLayout 的時候才會有 LinearLayout 的 Double taxation 發生。在其他狀況下，我們會想要拉平 Layout 層級，通用的理由遠比想像中單純 — 就是不希望讓 View tree 的走訪變複雜，但是如果開發可取的話，疊上一兩層也不是問題。</p><p>那話說回來， Compose 的 Column 和 Row 也可以在它們所屬的 Scope 底下的 Child 塞 modifier.weight 呀？那就不會發生 LinearLayout 的 double taxation 嗎？</p><p>先說結論：不會</p><p>為什麼呢？</p><p>這可以先從 Compose 的<a href="https://developer.android.com/jetpack/compose/phases">繪製流程</a>開始說起：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*wYmMIkIbCGojCkBn95LStA.png" /></figure><p>Composition ： 原則上就是把所有 Composable 的 function 全部跑過一遍，得到具體 UI 應該要怎麼佈局、怎麼繪製的資訊。附帶一提，Recomposition 的時候這邊會決定該 view tree node 要不要跳過 layout 和 drawing 的步驟。</p><p>Layout ：就是開始進行包括 measure 和 placement 的步驟，這個階段某個 tree view node 會知道自己和自己的 children view 應該怎麼擺放怎麼佈局</p><p>Drawing：就是大家都愛的繪製階段啦。</p><p>Modifier.weight 就包含在 composition 這個階段了，如果還記得上面所說 LinearLayout 需要 measure 兩次的理由的話，應該就可以理解這兩者之間的出入了。</p><p>以 LinearLayout 來說， measure 一次後才得到所需要對應的 weight 資訊，所以需要再 measure 一次，那 Compose 則是會得到所有所需要的 weight 資訊後才會開始 measure (Layout)</p><pre>@Composable<br>fun Jiugongge() {<br>    <em>Column </em><strong>{<br>        </strong><em>Row</em>(Modifier.<em>weight</em>(1f)) <strong>{<br>            </strong><em>Text</em>(<br>                modifier = Modifier.<em>weight</em>(1f),<br>                text = &quot;Just some demo.&quot;<br>            )<br>            <em>Text</em>(<br>                modifier = Modifier.<em>weight</em>(1f),<br>                text = &quot;Just some demo.&quot;<br>            )<br>            <em>Text</em>(<br>                modifier = Modifier.<em>weight</em>(1f),<br>                text = &quot;Just some demo.&quot;<br>            )<br>        <strong>}<br>        </strong><em>Row</em>(Modifier.<em>weight</em>(1f)) <strong>{<br>            </strong><em>Text</em>(<br>                modifier = Modifier.<em>weight</em>(1f),<br>                text = &quot;Just some demo.&quot;<br>            )<br>            <em>Text</em>(<br>                modifier = Modifier.<em>weight</em>(1f),<br>                text = &quot;Just some demo.&quot;<br>            )<br>            <em>Text</em>(<br>                modifier = Modifier.<em>weight</em>(1f),<br>                text = &quot;Just some demo.&quot;<br>            )<br>        <strong>}<br>        </strong><em>Row</em>(Modifier.<em>weight</em>(1f)) <strong>{<br>            </strong><em>Text</em>(<br>                modifier = Modifier.<em>weight</em>(1f),<br>                text = &quot;Just some demo.&quot;<br>            )<br>            <em>Text</em>(<br>                modifier = Modifier.<em>weight</em>(1f),<br>                text = &quot;Just some demo.&quot;<br>            )<br>            <em>Text</em>(<br>                modifier = Modifier.<em>weight</em>(1f),<br>                text = &quot;Just some demo.&quot;<br>            )<br>        <strong>}<br>    }<br></strong>}</pre><p>以這個例子來說，跑過一次 Composition 後，實際跑 Layout 會變成這樣</p><ol><li>Column 要求 measure</li><li>Column 要求自己的孩子，也就是第一個 Row 進行 measure</li><li>Row 要求自己的第一個孩子，也就是第一個 Text ，進行 measure</li><li>第一個 Text 沒有小孩，是末端節點，於是他利用 composition 階段得到的資訊給了自己的 Size 和放置位置</li><li>Row 要求自己的第二個孩子，也就是第二個 Text ，進行 measure</li><li>第二個 Text 沒有小孩，是末端節點，於是他利用 composition 階段得到的資訊給了自己的 Size 和放置位置</li></ol><p>…</p><p>9. 第一個 Row 底下的小孩測量大小和放置位置都畫完了，他可以決定自己的大小和利用 Composition 階段得到的資訊決定放置位置了，完成後回到 Column</p><p>10. Column 要求自己的第二個孩子，也就是第二個 Row 進行 measure</p><p>...</p><p>22. Column 底下的小孩測量大小和放置位置都畫完了，他可以決定自己的大小和利用 Composition 階段得到的資訊決定放置位置了，完成後結束這個 node 的 layout。</p><h3>結語</h3><p>聖誕節…我又在聖誕節寫了一篇文章了，雖然這篇文章相對於之前的文章短上許多。</p><p>其實還蠻有意思的，半年前我提的疑問，在半年後我因緣際會回碰到 Double taxation 之後得到了對應的解答。我當時看的角度是，所有的 Layout 在跌太多層之後都有可能有 Double taxation 的問題，那麼 compose 疊很多層是不是也會有這種問題呢？後來細看才發現，double taxation 並不是因為疊很多曾造成的問題，疊很多層只是加重這個問題。LinearLayout 有會有這問題，GridLayout 也會有這個問題，但兩者發生的情況卻不太一樣，所以若想理解這方面的東西得把這東西發生的原因找出來才能對應的理解為什麼 Compose 不會發生類似的事情。因此我理解到，在這方面我會覺得知道為什麼會比知道怎麼辦來的更重要。</p><p>在這邊我們可以知道，Compose 和傳統 View 最大的不同是，傳統 View 會丟給 Child 去算，但資訊不夠的情況下，需要讓 Child 再算一次；而 Compose 則是會讓其 children 交代好再自己去算。</p><p>如果有任何問題，或是看到寫錯字，請不要吝嗇對我發問或對我糾正，您的回覆和迴響會是我寫文章最大的動力。</p><h3>參考文章</h3><p><a href="https://developer.android.com/jetpack/compose/phases">https://developer.android.com/jetpack/compose/phases</a></p><p><a href="https://developer.android.com/topic/performance/rendering/optimizing-view-hierarchies">https://developer.android.com/topic/performance/rendering/optimizing-view-hierarchies</a></p><p><a href="https://developer.android.com/jetpack/compose/layouts/basics">https://developer.android.com/jetpack/compose/layouts/basics</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3691580e828c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jastzeonic/jetpack-compose-layout-%E5%B1%A4%E7%B4%9A%E6%9C%83%E6%9C%89-double-taxation-%E5%97%8E-%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-3691580e828c">Jetpack Compose Layout 層級會有 Double taxation 嗎？那一兩件事情</a> was originally published in <a href="https://medium.com/jastzeonic">Jastzeonic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose Recomposition 那一兩件事情]]></title>
            <link>https://medium.com/jastzeonic/jetpack-compose-recomposition-%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-7782f1f35ed8?source=rss-b868b6eecf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/7782f1f35ed8</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jast Lai]]></dc:creator>
            <pubDate>Sun, 28 Nov 2021 15:22:48 GMT</pubDate>
            <atom:updated>2021-11-28T15:23:35.598Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jetpack Compose Composition 和 Recomposition 那一兩件事情</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPJtzevRQvg_EblUyIl1wg.jpeg" /></figure><blockquote>在此之前，我一直以為使用 compose 能和使用 Flutter 一樣，只要能夠讓他更新 State 就好，直到我發現事情並不是這樣…<br>- Jast Lai</blockquote><h3>前言</h3><p>Jetpack Compose 可以算是 Flutter 的攣生兄弟，我常常這樣說，但是兩者顯然還是有差別的，而且這差別直到我在接觸需要使用動畫的時候才發現。</p><p>之前我使用 Flutter ，我要把一個自從左移到右邊，</p><pre>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  double padding = 0.0;<br><br>  void _incrementCounter() {<br>    runMoveAnimation();<br>  }<br><br><strong>  Future runMoveAnimation() async {<br>    for (var i = 0; i &lt; 100; i++) {<br>      await Future.delayed(Duration(milliseconds: 10), () {<br>        padding += 0.4;<br>        setState(() {});<br>      });<br>    }<br>  }</strong><br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(widget.title),<br>      ),<br>      body: Column(<br>        mainAxisAlignment: MainAxisAlignment.center,<br>        children: genText(),<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _incrementCounter,<br>        tooltip: &#39;Increment&#39;,<br>        child: Icon(Icons.<em>add</em>),<br>      ), // This trailing comma makes auto-formatting nicer for build methods.<br>    );<br>  }<br><br><strong>  List&lt;Widget&gt; genText() {<br>    return List&lt;Widget&gt;.generate(<br>        35,<br>        (index) =&gt; Padding(<br>            padding: EdgeInsets.only(left: padding),<br>            child: Text(&quot;Text&quot;)));<br>  }</strong><br>}</pre><p>那可以看到我每次 setState ，都會更新一次我設定的 padding ，運用 delay 達到每次增加一點 padding 的效果來製造 text 移動的假象。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_Nye6YS4bYU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_Nye6YS4bYU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_Nye6YS4bYU%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/e15b3536434aaffdc6cde3bff8ce8336/href">https://medium.com/media/e15b3536434aaffdc6cde3bff8ce8336/href</a></iframe><p><em>PS:當然我 Flutter 是用 Release 版的，開 Debbug 會有奇妙的延遲狀況，這個我想有玩過 Flutter 都很清楚</em></p><p>只是我用了相同的邏輯，到了 Compose 卻發生了一點問題：</p><pre>class MainActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        <em>setContent </em><strong>{<br>            </strong><em>Greeting</em>()<br>        <strong>}<br>        </strong><em>lifecycleScope</em>.<em>launch </em><strong>{<br>            </strong>delay(1000)<br>            var takeTime = System.currentTimeMillis()<br>            <em>repeat</em>(100) <strong>{<br>                </strong>delay(50)<br>                <em>animationPoint</em>.value = <em>animationPoint</em>.value + 1<br>            <strong>}<br>            </strong>takeTime = System.currentTimeMillis() - takeTime<br>            Log.v(&quot;tag&quot;, &quot;end $takeTime&quot;)<br>        <strong>}<br>    </strong>}<br>}<br><br>var <em>animationPoint </em>= <em>mutableStateOf</em>(0)<br><br>@Composable<br>fun Greeting() {<br>    <em>LogCompositions</em>(&quot;tagtag&quot;, &quot;&quot;)<br>    <em>Surface</em>(<br>        modifier = Modifier<br>            .<em>fillMaxWidth</em>()<br>            .<em>offset</em>(x = <em>animationPoint</em>.value.<em>dp</em>)<br>    ) <strong>{<br>        </strong><em>Column </em><strong>{<br>            </strong><em>repeat</em>(40) <strong><br></strong><br>                <em>Text</em>(&quot;Text ${<em>animationPoint</em>.value.<em>dp</em>}&quot;)<br>            <strong>}<br><br>        }<br>    }<br></strong>}</pre><p>那結果如下：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAvhPvkQCTQY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAvhPvkQCTQY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAvhPvkQCTQY%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/8904822d6942d994f123922bd4d4b685/href">https://medium.com/media/8904822d6942d994f123922bd4d4b685/href</a></iframe><p>那其實可以看得出來，開頭有一點點微妙的 Delay … 這不禁讓人納悶了，難不成 Flutter 在這方面技高一籌？</p><h3>關於 MutableState 那一兩件事情</h3><p>Jetpack Compose 畢竟還是依著 Android Native view 而生的，很多地方還是得依循著 Android Native 的原則。如果跟我一樣，在碰過 Flutter 後再去寫 Compose，當我需要跟 Flutter 一樣用 setState 來去更新狀態時，會赫然發現根本沒有類似 setState 之類的東西可以使用。</p><p>取而代之的是 MutableState ，接著就會有很奇妙的語法出現：</p><pre>@Composable<br>fun Greeting() {<br><strong>    var rememberValue by <em>remember </em>{<br>        <em>mutableStateOf</em>(0)<br>    }<br>    </strong><em>LogCompositions</em>(&quot;tagtag&quot;, &quot;&quot;)<br>    <em>Surface</em>(<br>       // ...ignore</pre><pre>    )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*kwMv3H_7YDGwA4tqTXcxTQ.jpeg" /></figure><p>這都啥玩意阿？要我在一個 function 裏頭記住這個 value ？</p><p>但這倒是可以從 remember 這個 method 的說明得到一點線索。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*IhN512z6MdsY6VxGnVWmVg.png" /></figure><blockquote>Remember the value produced by calculation. calculation will only be evaluated during the composition. Recomposition will always return the value produced by composition.</blockquote><p>記住藉由計算出來的結果。計算只會在 composition 的時發生，Recomposition 會回傳在 composition 產生時的 value。</p><p>Composition ？ Recomposition ？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*aAaIO-xwOiDQlwWh.png" /></figure><p>先從這兩個名詞開始解釋吧。</p><p>一開始弄一個畫面時，我們依照 Compose 本身的寫法，把 Layout 給弄出來，以上面那個例子為主，我們利用 Column 把 40 個 Text 給畫到畫面上。</p><p>那可以看到是透過 Activity 的 onCreate 呼叫一個叫做 setContent 的東西在裏頭呼叫 Greeting() 把畫面畫上去的。</p><pre><em>setContent </em><strong>{<br>    </strong><em>Greeting</em>()<br><strong>}</strong></pre><p>setContent 原則上跟大家都很熟的 setContentView 一樣，只是到這轉成使用 ComposeView 了，這對 Compose 來說，在啥都沒有的情況下把 ComposeView 弄上去，呼叫 annotation composable 的 method ，這個動作叫做 Composition。</p><p>那問題來了，我 Text 甚麼的都在 onCreate 的時候呼叫到了，那我要更新某個 Text 的時候要怎麼辦？</p><p>再呼叫一次 setContent {} 嗎？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*V0yi-osPVcd6oPMAqz6Fqg.png" /></figure><p>有意思的地方是在 compose 建立之後，在這邊就會被攔截掉了，雖然這個 method 被 deprecate 了，也許會來會變，但目前就是這樣，所以不能寄望用 setContent 來更新 View 的 state 了。</p><p>那有甚麼方法呢？</p><p>用 MutableState 。</p><p>這玩意跟 LiveData 類似，只是整體過程看起來更玄學，有機會再來做解釋好了。總之，當你 assign 他的 Value 他會 trigger 有下 Annotation 的 composable 的 function。</p><p>例如：</p><pre>var <em>text </em>= <em>mutableStateOf</em>(&quot;Hello&quot;)<br><br>@Composable<br>fun Greeting() {<strong><br></strong>    <em>Surface</em>(<br>        modifier = Modifier .<em>fillMaxWidth</em>()<br>    ) <strong>{<br>        </strong><em>Column </em><strong>{<br>            </strong><em>Text</em>(<em>text</em>.value)<br>        <strong>}<br>    }<br></strong>}</pre><p>那我如果寫了</p><pre><em>text.value = &quot;Hello 2&quot;</em></pre><p>則會觸發：</p><pre><strong>@Composable<br>fun Greeting() {<br>    <em>Surface</em>(<br>        modifier = Modifier.<em>fillMaxWidth</em>()<br>    ) {<br>        <em>Column </em>{<br>            <em>Text</em>(<em>text</em>.value)<br>        }<br>    }<br>}</strong></pre><p>整個 Greeting() 被 invoke ，這個過程我們稱為 Recomposition。那這個 Text 也被成功的更新顯示成 Hello 2。</p><p>只是有意思的地方在這裡，這邊看起來跟 Flutter 的 setState 很類似，但是事實上兩者還是有區別的，我一直在說 Compose 和 Flutter 像是攣生兄弟，Widget 得名字都相似，但是兩者在根本層面上還是有出入，我目前碰到最大的出入就是 state 管控上。</p><p>Flutter 會根據 widget 輸入的 parameter 做 diff，來決定 widget 要更新甚麼，所以可以直接用 setState 來更新整個 UI tree。而 Compose 雖然也可以這樣可以，但對 Compose 來說，<a href="https://developer.android.com/jetpack/compose/mental-model#recomposition"><strong>更新整顆 UI tree 非常昂貴</strong></a>。我猜是因為 draw 的方式不同，Compose 應該還是依賴 Android Native 的 canvas 而有所限制，不能很單純的 diff parameter，具體還得再研究。所以 Compose 會更傾向 Recomposition 需要的 Composable。</p><p>以上面的例子來說，會 Recomposition 到整個 Surface ，那其實有點沒有必要，這邊可以改寫成這樣：</p><pre>var <em>text </em>= <em>mutableStateOf</em>(&quot;Hello&quot;)<br><br>@Composable<br>fun Greeting() {<br>    <em>Surface</em>(<br>        modifier = Modifier.<em>fillMaxWidth</em>()<br>    ) <strong>{<br>        </strong><em>Column </em><strong>{<br></strong>            <em>genText</em>()<br>        <strong>}<br>    }<br></strong>}<br>@Composable<br>fun genText() {<br>    <em>Text</em>(<em>text</em>.value)<br>}</pre><p>這樣便可以把 Recomposition 的範圍限制在 genText() 內，不會把範圍擴大到 Surface 和 Column 那頭。</p><p>那可能有人會好奇了，如果說今天寫成這樣：</p><pre>var <em>text </em>= <em>mutableStateOf</em>(&quot;Hello&quot;)<br><br>@Composable<br>fun Greeting() {<br>    <em>Surface</em>(<br>        modifier = Modifier.<em>fillMaxWidth</em>()<br>    ) <strong>{<br>        </strong><em>Column </em><strong>{<br></strong>            <em>genText</em>()<br><em>            Text</em>(<em>text</em>.value)<br>        <strong>}<br>    }<br></strong>}<br>@Composable<br>fun genText() {<br>    <em>Text</em>(<em>text</em>.value)<br>}</pre><p>那這樣我更新 text會發生甚麼事情？</p><p>這樣也只會更新一次而已，範圍是 Greeting() 下至 genText()。genText() 並不會單獨再跟新一次</p><p>通常更新到的部分會以最外層，又或者以比較資結的語言說：只會更新最接近 UI tree 最接近 root node 的 composable method 為優先 Recomposition。</p><p>但說昂貴是昂貴，若不是在使用到動畫這種需要精準控制到每一個 Frame 、重畫很多 Compose 的時候，也就不需要這麼刻意去減少 Recomposition 的範圍就是了，在使用上需要知道自己在做甚麼，而是自己眼下的情況去做改變，不要太過滑坡認為一律要盡可能減少 Recomposition 就是了。</p><h3>那 by Remember 是啥玩意？</h3><p>那話說回來 Remember 那又是啥鬼玩意？</p><p>現在對 Recomposition 有概念了，我們再回來看這段話：</p><blockquote>Remember the value produced by calculation. calculation will only be evaluated during the composition. Recomposition will always return the value produced by composition.</blockquote><p>一開始我們 setContent 在甚麼都沒有的情況下生成 Compose 時叫 composition ，透過 MutableState 的 setValue trigger 已存在的 Compose 更新其 state 叫做 recomposition。也就是說使用 remember 產生的 MutableState ，在 recomposition 時，並不會被重新生成，而是沿用一開始那個。</p><p>這有啥用呢？我們很常會有一整排 View 都需要被管控的時候，但是實際上該 View 的狀態只會在某個 Compose 的範圍內會被影響到，那如果那時候需要一整排 MutableState 當成 Global value 也是挺擾人的。例如我有一個 TextField ，下面有個按鈕只有在 TextField 有字時才能按，那會寫成這樣：</p><pre>var <em>text </em>= <em>mutableStateOf</em>(&quot;&quot;)<br><br>@Composable<br>fun Greeting() {<br>    var enableButton by <em>remember </em><strong>{<br>        </strong><em>mutableStateOf</em>(false)<br>    <strong>}<br>    </strong><em>Surface</em>(<br>        modifier = Modifier.<em>fillMaxWidth</em>()<br>    ) <strong>{<br>        </strong><em>Column </em><strong>{<br>            </strong><em>TextField</em>(value = <em>text</em>.value, onValueChange = <strong>{<br>                </strong>enableButton = <strong>it</strong>.<em>isNotEmpty</em>()<br>                <em>text</em>.value = <strong>it<br>            }</strong>)<br>            <em>Button</em>(<br>                onClick = <strong>{ }</strong>,<br>                enabled = enableButton<br>            ) <strong>{<br>                </strong><em>Text</em>(text = &quot;Button&quot;)<br><br>            }<br><em>            Text</em>(<em>text</em>.value)<br>        <strong>}<br>    }<br></strong>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*9hvOhAxC1P-Xgp87V-MBDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*9hvOhAxC1P-Xgp87V-MBDA.png" /></figure><p>那看起來 Code 跑起來跟我想的一樣，這樣就解釋了 remember 的目的了。</p><h3>結語</h3><p>認真地說，如果不是認為 Jetpack compose 跟 Flutter 類似，然後用類似的做法去做了動畫，也就不會踩到這個坑了，也就不會藉此瞭解所謂的 Recomposition 和 remember 的目的了。</p><p>說來也有趣，上頭那個動畫是相當極端的狀況，即便真得要搞一個遊戲的動畫也不太可能碰到這情況就是了(所以我還沒想到方法讓 Compose 版跑得跟 Flutter 版一樣順暢，畢竟只是範例而已)。但說實話，如果真的要用 Compose 搞一個相當動態的畫面時，目前情況還是需要避免不必要的 Recomposition 就是了。</p><p>如果有任何問題，或是看到寫錯字，請不要吝嗇對我發問或對我糾正，您的回覆和迴響會是我寫文章最大的動力。</p><h3>參考文章</h3><p><a href="https://developer.android.com/jetpack/compose/mental-model">https://developer.android.com/jetpack/compose/mental-model</a></p><p><a href="https://www.jetpackcompose.app/articles/donut-hole-skipping-in-jetpack-compose">What is &quot;donut-hole skipping&quot; in Jetpack Compose?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7782f1f35ed8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jastzeonic/jetpack-compose-recomposition-%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-7782f1f35ed8">Jetpack Compose Recomposition 那一兩件事情</a> was originally published in <a href="https://medium.com/jastzeonic">Jastzeonic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter render 的那一兩件事情]]></title>
            <link>https://medium.com/jastzeonic/flutter-render-%E7%9A%84%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-d372ed9a9962?source=rss-b868b6eecf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/d372ed9a9962</guid>
            <category><![CDATA[elements]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[renderobject]]></category>
            <dc:creator><![CDATA[Jast Lai]]></dc:creator>
            <pubDate>Fri, 22 Oct 2021 11:07:03 GMT</pubDate>
            <atom:updated>2021-10-22T11:07:03.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*7wNoqNuqkROYAzInZzFv8A.jpeg" /></figure><h3>前言</h3><p>上回寫了 Jetpack compose 後，我很好奇，為什麼 compose 的 composable 可以像不用錢似的一直 instance。</p><p>我想起了之前稍微碰了一下的 Flutter ，原則上 Jetpack compose 和 Flutter 都是 Google 的攣生兄弟，他們兩個都是都是宣告式的語法，然後因為 Widget 和 composable 都被設定為不可異動，所以更新它們 UI 的方式好像不用錢似的每次刷新每次都是一個新的 instance 。</p><p>這令我好奇心蠢蠢欲動，於是我開始追 Code ，然後看文件，追一些文章，後來理出這篇文章，應該可以稍微解釋一下，究竟是甚麼原因，可以讓 Widget 這些東西可以不斷被重新 instance。</p><h3>先來看看怎麼建立一個 App</h3><p>Dart 是從 main 開始的，透過 runApp 這個 method 去把做為 app 的Widget 給建構出來 -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*c1q_KWdvaCAJ5kR2Hn_2qA.png" /></figure><p>寫 Android 寫久了，看到 main 會莫名的覺得有點新鮮。不過 Android 沒 main 是 Android 那很不一樣的架構所致的，否則 main 應該都會作為大多數應用程式起始點，至於 Android App 那很不一樣的起始那又是另一個故事了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*TOyg93xjeee6xAeOqujP0w.png" /></figure><p>可以注意到， runApp 本身是一個 top-level-functions，那他會做的事情是去初始化建構一個 WidgetsFlutterBinding ，那麼之後 Widget 的更新等等操作都會在這邊去做處理。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*Xz55RgLvPGa-Wyf-bHJ-Mg.png" /></figure><p>先不要管排程這件事情，總之這裡 runApp 要做的事情呢，就是要把傳進來的 RichText 當作是 rootWidget</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*V0Po9RQlUUSzXK9ButuxPw.png" /></figure><p>要怎麼做才能成為 root widget 呢？追下去，可以注意到，這裡要利用這個 widget 去建立 element，在 attachRootWidget 的時候，這裡實作了一個叫做 RenderObjectToWidgetAdapter 的 widget，並把 RichText 作為 child 傳入，接著呼叫了一個叫做 attachToRenderTree 的地方。</p><p>只是這時的 renderViewElement 是伴隨著 WidgetsFlutterBinding 被宣告的，但還沒有被實作，所以會是 null，那會發生甚麼事情呢？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*D1puibO_cCzS45BBJAKmHw.png" /></figure><p>他會去呼叫 createElement()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*mpjZhHmzTGeSEqVEPshsfg.png" /></figure><p>createElement() 會實作並回傳一個叫做 RenderObjectToWidgetElement 的 Element，並把 RenderObjectToWidgetAdapter 作為 Property 傳入。</p><p>接著看下去，會發現被建立出來的 Element 呼叫了 mount ，這裡應該是安裝的意思，那來看一下 mount 具體做了甚麼事情：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*Q-RLwuuXtggtS9yemNdHpQ.png" /></figure><p>可以看到這邊利用剛才作為 property 傳入的 RenderObjectToWidgetAdapter 呼叫 createRenderObject，並且把 Element 當成 Property 傳入他的 constructor 之中。</p><p>看到這邊會發現，三個在 Flutter render 系統的大名鼎鼎的 Widget 、Element、RenderObject 都出現了，他們之間的關係真的不是普通的亂，但還沒完呢。</p><p>呼叫了 RenderObjectToWidgetAdapter 的 createRenderObject 拿到的會是甚麼？是隨著 WidgetsFlutterBinding 一同產生一個叫做 renderView 的 RenderObject。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*JficR40rMEfac3QVEVT1Qg.png" /></figure><p>這個 container 正是 RenderObjectWidgetAdapter 在實作產生 RenderObjectToWidgetElement 傳入的 renderView，這個怎麼來的待會解釋。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*V0Po9RQlUUSzXK9ButuxPw.png" /></figure><p>做完上面這些行為後，RenderObjectToWidgetElement 會在尾巴呼叫一個叫做 _rebuild 的 private method。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*ac-mKvZpT4SBePwMY-_dgQ.png" /></figure><p>可以看到這時的會做一個 update child 的動作。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*XV7RyDrtjVk38zErVUirtg.png" /></figure><p>這時只要知道 widget.child 是誰呢？先來看看 widget 是誰？沒錯，就是 RenderObjectToWidgetAdapter ，那 RenderObjectToWidgetAdapter 的 child 是誰？一卡檸檬，正是 RichText。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*Tnx9PmH4rBIPYb5D78mCsw.png" /></figure><p>可以發現會進到 inflateWidget</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*O0CCQlbjnxmBsyYIRNL4Pg.png" /></figure><p>裏頭會用 RichText 這個 Widget 呼叫 createElement ，建立一個 MultiChildRenderObjectElement ，同時會把自己當成 property 傳進去 MultiChildRenderObjectElement 裏頭。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*r436MAlXs15hWStPluZkuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*je3i1i7ZEBoxOdiS_q4h4A.png" /></figure><p>接著會用 MultiChildRenderObjectElement 做 mount ，這裡只要知道 this 就是 RenderView，作為 parent 傳入這個 method。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*YxObmLm8-Zpu4rT1GlCG3w.png" /></figure><p>很有趣，似乎又繞回了 RenderObjectElement (RenderObjectElement 是 RenderObjectToWidgetElement 的繼承類別，但這邊先別管這個)，那可以注意到這裡利用 widget 。也就是 RichText 建立了一個 RenderObject 叫做 RenderParagraph ，記得是由 MultiChildRenderObjectElement 拿著 RenderObject，而非 widget。</p><p>接著來到 attachRenderObject</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*X-qoE3Ilf_On5SJSNBMXxQ.png" /></figure><p>這邊會找一個 Ancestor (祖先) 的 RenderObjectEelement ，還記得傳進來的 parent 是誰嗎？沒錯，正是 RenderObjectToWidgetElement。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*bRCs0pn3MIcOlAQphnbKJw.png" /></figure><p>RenderObjectToWidgetElement 的 RenderObject 是誰呢？正是 WidgetsFlutterBinding 的 renderView 。 此時終於把 RichText 的 RenderObject 和 WidgetsFlutterBinding 的 RenderObject renderView 綁在一起了。</p><p>簡單的整理一下我們上面得到的資訊，</p><ul><li>塞了一個 Widget 給 runApp</li><li>產生一個 WidgetsFlutterBinding (如果現存為 null 的話) 附帶一個 renderView ，他正是 WidgetsFlutterBinding 的 RenderObject</li><li>產生 RenderObjectToWidgetAdapter 。</li><li>利用 RenderObjectToWidgetAdapter 產生 RenderObjectToWidgetElement 並將 RenderObjectToWidgetAdapter 作為 RenderObjectToWidgetElement 的 property。</li><li>RenderObjectToWidgetElement 會產生當初 runApp 傳入的 Widget 的 Element 。</li><li>利用 Widget 產生出來的 Element 透過 Widget 產生 RenderObject。</li><li>利用 RenderObjectToWidgetElement 將 Widget 的 RenderObject 變成 WidgetsFlutterBinding 的 renderView 的 child ，並將其作為 root widget。</li></ul><p>好，知道這些，我們可以了解到 RenderObject 是透過 Element 利用 Widget 產生出來的，而 Element 則是由 Widget 產生出來的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*TOyg93xjeee6xAeOqujP0w.png" /></figure><p>在做完綁定後，接著的 scheduleWarmUpFrame 就會開始把 widget 提供的資訊 render 畫面了。</p><h3>那 RenderObject 是啥玩意阿？</h3><p>說到 RenderObject ，那可以來看看 RenderView 是幹嘛的。</p><p>在 runApp 時，建立了 WidgetsFlutterBinding ，那這個 WidgetsFlutterBinding 同時含有一個叫做 RenderBinding 的 mixin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFtVMoDM-fxb5SZCK537oQ.png" /></figure><p>那麼 RenderBinding 就在生成的過程中同時產生了 RenderView。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*Q3Adg13GYmVj5klyXRdYxw.png" /></figure><p>那顯然 RenderView 會負責把他的 Child 給畫到畫面上。</p><p>那會怎麼畫取決於 Child 是甚麼樣的 RenderObject：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tctGFZTx5KUlBfYA_Dm36g.png" /></figure><p>RenderObject 在呼叫 PainWithContext 後會呼叫到 paint ，以 RichText 來說，他的 RenderObject 是 RenderParagraph ，那他的 paint 大概是這樣：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*RQPvvz8ezoMfb4HsZ0CwIw.png" /></figure><p>有玩過 Android View 人對上面的 canvas 阿，drawRect 等等應該都不陌生。</p><p>可見 RenderView 就是 runApp 時所產生，算是一個 App 裡原初的 RenderObject。</p><p>像是 Column ，他的 RenderObject 叫做 RenderFlex ，RenderFlex 的 paint 會呼叫 defaultPaint ，那 defaultPaint 就會開始去呼叫他的 child 並繪製他。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*UgrXDUgrEmX-7PHH65KJlA.png" /></figure><p>講到這裡，如果對 View Tree 有概念的話，腦海應該浮現了一個樹狀圖。</p><p>我以這個簡單的 MaterialApp 來舉例：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*rgo0trtd9_q2vUKOM6-oqQ.png" /></figure><p>MaterialApp 是 StatefulWidget ，StatefulWidget 和 StatelessWidget 跟 RichText 比較不一樣，它們並不需要建立 RenderObject ，主要是因為他們要 Render 的對象是它們提供出來的 Widget ，這邊不深究(雖然待會會提及一點 State 的部分)，所以這個簡單的 App 的 RenderObject tree 只要看 _MyHomePageState build 的部分。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqA8DTqikF8C8leOk-ZYXA.jpeg" /></figure><p>假如 RichText 是一個 Android 的 View ，那麼在 Android 裏頭，會用 findViewById 去把它弄成一個 field 然後放到 control flow (Activity, fragment) 去操作。</p><p>又回到了最初的問題了，這樣我建立一個 Widget 豈不是每次都要重新建一個 RenderObject 然後去 layout 接著 draw 。</p><p>StatefullWidget 呼叫一次 setState 成本不是嚇死人了？</p><p>好，請聽我娓娓道來。</p><p>到目前為止，RenderObject 看起來跟用 Native 的 View 很像，雖然可能還是沒有很懂為啥需要有個 Widget 和 Element。那回到最初的問題：為什麼 Flutter 的 Widget 可以像是不用錢一樣的，每次都給一個新的 instance 呢？上面的敘述只是稍微弄清了 Widget、Element、RenderObject 三者的關係，那具體到底怎麼辦到的呢？</p><p>PS: 嚴格說起來還是要點花費，只是成本相對低很多</p><h3>來理解三者的關係吧</h3><p>這邊簡單弄一個可以 set State 的 App</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*tJnbrNbOc7C_oZsIPf0tPw.png" /></figure><p>我在按下 TextButton 後，會觸發 setState ，經歷了很長一段在這邊不談的程式碼後，接著會在會重新呼叫到 build(BuildContext)，然後拿去跟</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*GrB0IK-wCqn3IGNC3DgFiw.png" /></figure><p>updateChild 的時候呢，就會比對這個 Widget 是不是一樣(主要是比對 widget 的類型還有 key，而 key 絕大部分時候都是 null)？是不是能夠更新？或者是需要插入另一個新的 Widget 呢？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*6bAqLiOUO2ph7A2eATtXVQ.png" /></figure><p>樹一層一層被遞迴來到了 RichText 的 Element 後，會呼叫 Widget 的 updateRenderObject</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*Nr2d3rw4iPgBg5lf4O_KYg.png" /></figure><p>在這裡就決定了，甚麼東西需要重畫，甚麼東西不用(雖然把全部的 Property 全 assign 了一次了，但是每一個 property 都有判斷值相不相同，所以原則上這邊需要重畫的只有 text)。</p><p>有意思的地方來了，還記得前面說過，這邊的 Widget 是誰拿著的？那這邊的 RenderObject 又是誰拿著的。</p><p>沒錯，都是 Element 。</p><p>簡單來說，runApp 完後，大致上的局勢是這樣的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fk1F1q5eVgAfjgtxZBWb6Q.jpeg" /></figure><p>在 setState 的時候， MyHomePage’s 的 StatefulElement 會得到一個新的 Widget。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1qTM-YjEcSobrJOi4SCFQ.jpeg" /></figure><p>那麼 Element 會往下丟給它的 Child。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgGDhExW2bHVOlTUf1c2ag.jpeg" /></figure><p>這邊確定一樣後，就繼續往下丟給它的 Child。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEsE_YwIRsYo-eANuPwTjA.jpeg" /></figure><p>這邊會問能否 update ，原則上兩個類型一樣就會 update 了，所以會送給 Element 的 RenderObject ，而 RenderObject 再比對有沒有 Property 不同，再去決定甚麼東西要重畫。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NG74D-bmYFMl6cELaEJasA.jpeg" /></figure><p>TextButton 也差不多，只是很顯然 TextButton 在此時沒有東西要重畫。</p><p>回過頭來改一下 Code ：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*Qn4RqPba9NM50w8heE_gNg.png" /></figure><p>我如果按了一下按鈕，會把原本的 TextButton 給取代為另一個新的 RichText 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vRr6o2AhXN_PoSiNK5mryQ.jpeg" /></figure><p>一開始 MyHomePage 得到新的一個 Column ，他把他往下給他的 Child — 原本的 Column：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIh5WHLGniv9dEPp8HOSig.jpeg" /></figure><p>對於 Column 的 Element 來說，他會發現，喔喔，我的 child 被換掉了，那舊的 child 我不要了，把 Element 連同 RenderObject 一起丟了，我需要重新 layout 來放新的 child。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9KRyZPB807u11DSG1eP2g.jpeg" /></figure><p>這裡先略過做完更新原有 RichText 的步驟。新的 child 得產生新的 Element 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EJYyHnh8D3oNKCe9CChUQ.jpeg" /></figure><p>新的 Element 需要新的 RenderObject ，於是就走了 inflateWidget 的流程，產生新的 RenderObject ，接著把 RichText 給畫出來了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bD2XE49GbnPmddwwufmnrA.jpeg" /></figure><h3>結語</h3><p>說了這麼多，大概可以說明一下 ，Widget、Element、RenderObject 是甚麼了？</p><p>RenderObject 就是負責繪圖。說碰到它很昂貴有點沉重，基本上畫面有變就會動到他，它至少會去比對 Property 有沒有不一樣、要不要重繪。所以實際上還是很常碰到 RenderObject ，但在理論上在寫 Flutter 的時候不太容易直接碰到它就是了。</p><p>Element 可以當作是當前 Widget 還有 RenderObject 的狀態持有者。雖然官方文件說它是 Widget 的 instantiation，但它並不是 Widget widget = new Element(); 這種關係。Widget 的 instantiation 需要有一個 RenderObject 和自身 Widget 的設定，Element 負責這事情，所以 Element 是 widget 的 instantiation。那麼Flutter 是跨平台的框架，但是主力是在兩個手機雙平台上，雙平台基本上不可避免生命週期的東西，那 Element 他持有 Widget 和 RenderObject 的狀態，應該也可以猜到<strong>它會負責生命週期</strong>的東西，但不是這篇的重點，這邊就不贅述了。</p><p>Widget 理論上會是 Flutter 開發者最常碰到的東西。那他其實除了負責持有 RenderObject 應該要怎麼 layout 怎麼 render 的資訊外。此外他還會持有怎麼產生自己的 element ，且根據 element 而定(像 Statefulwidget，他是會另外產生 Widget ，所以他並不需要產生 RenderObject)，他也會需要知道怎麼建立屬於他的 RenderObject 以及怎麼 updateRenderObject，<strong>那</strong>這些事情都是由它產生的 Element 或是做為他的 parent 的 Element 去做的，包括產生自己的 Element ，instance widget 本身並不會做這些事情，所以，<strong>產生一個新的 widget instance 是很廉價，因為產生他只會生成資料不會直接生成 Element 和 RenderObject</strong>，昂貴與否得看你怎麼去變動你的 layout widget 那些。</p><p>知道這些後，就知道為什麼 Widget 可以像不用錢似的不斷重新 instance ，因為本質上他就是一個設定檔、或者說藍圖的存在。小生我對於 Web 前端並不太熟，但這個模式跟 DOM 好像類似就是了。</p><p>如果有任何問題，或是看到寫錯字，請不要吝嗇對我發問或對我糾正，您的回覆和迴響會是我寫文章最大的動力。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d372ed9a9962" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jastzeonic/flutter-render-%E7%9A%84%E9%82%A3%E4%B8%80%E5%85%A9%E4%BB%B6%E4%BA%8B%E6%83%85-d372ed9a9962">Flutter render 的那一兩件事情</a> was originally published in <a href="https://medium.com/jastzeonic">Jastzeonic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>