<?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 Minseon Cho on Medium]]></title>
        <description><![CDATA[Stories by Minseon Cho on Medium]]></description>
        <link>https://medium.com/@seoon53?source=rss-6d057e5de27c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eCTESqw8-sQE5QxzaxJIcw.jpeg</url>
            <title>Stories by Minseon Cho on Medium</title>
            <link>https://medium.com/@seoon53?source=rss-6d057e5de27c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:23:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seoon53/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[[Compose] How to Match Design and Text Height in Compose  — LineHeightStyle]]></title>
            <link>https://medium.com/@seoon53/compose-how-to-match-design-and-text-height-in-compose-lineheightstyle-ddb725e31ffe?source=rss-6d057e5de27c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddb725e31ffe</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[lineheightstyle]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[figma]]></category>
            <category><![CDATA[jetpack-compose-tutorial]]></category>
            <dc:creator><![CDATA[Minseon Cho]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 07:31:05 GMT</pubDate>
            <atom:updated>2024-11-25T06:23:52.039Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Compose] How to Match Design and Text Height in Compose 😉 — LineHeightStyle</h3><p>When working with Compose, it’s common to predefine text styles using TextStyle for your app. However, you might have noticed subtle differences between your designs and the actual implementation, even after setting lineHeight in your TextStyle.</p><p>This is because, on Android, lineHeight is defined as the distance between text baselines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*3rFvGRreULk8LkLppOD-6g.png" /><figcaption>The common understanding of lineHeight</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*JOcl21RcX9OWGCPLo4EELQ.png" /><figcaption>Android’s definition of lineHeight (distance between baselines)</figcaption></figure><p>As a result:</p><ul><li>For single-line text, lineHeight doesn’t apply because there’s no baseline above or below the line.</li><li>For multi-line text, lineHeight won’t apply to the top of the first line or the bottom of the last line because those areas don’t have baselines either.</li></ul><p>However, in tools like Figma, lineHeight behaves as in the first definition above, which creates inconsistencies between design and development.</p><p>You can resolve this discrepancy through TextStyle in Compose.</p><h3>Understanding LineHeightStyle in TextStyle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vbr1kTIoFed0R3hbRiblWA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRbY0F4JJWRNT6rShvDghw.png" /></figure><p>When you inspect the TextStyle code, you’ll find an attribute called lineHeightStyle.</p><p>If you pass null to lineHeightStyle, the default LineHeightStyle is applied. By default, its trim value is set to Trim.Both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vk3FgxzYFqY62Us5J5J2FQ.png" /></figure><p>The Trim class has four constants, and here’s the explanation for Trim.Both:</p><blockquote><em>“Removes extra space added by the line height above the first line and below the last line.”</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*Tbim8I-68peMBSNWGtLWXA.png" /><figcaption>Single-line text</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*zVQexSbosolhSbWfXoa8Qw.png" /><figcaption>Multi-line text</figcaption></figure><p>The yellow areas in the images above represent the extra space removed by the default Trim.Both setting.</p><p>This is why the text height in Figma looks different from what you see in the app.</p><p>To ensure the line height remains consistent, you can change this setting to Trim.None so the extra space above and below isn’t removed.</p><h3>Aligning text vertically within the height</h3><p>Even after setting this up, the actual text rendering might not be perfectly centered vertically within the height.</p><p>This is where the Alignment property of LineHeightStyle comes into play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apnRzTTEJi1o7mTLkQtuOw.png" /></figure><p>By default, Alignment is set to Proportional, which follows the font metrics and may not position the text in the center.</p><p>Switching this to Alignment.Center ensures the text is centered vertically within its height.</p><h3>Here’s how you can define your lineHeightStyle:</h3><pre>val lineHeightStyle = LineHeightStyle(<br>    alignment = LineHeightStyle.Alignment.Center,<br>    trim = LineHeightStyle.Trim.None<br>)</pre><p>By configuring lineHeightStyle as shown above, you can ensure that your app’s text height matches Figma’s design precisely. 🥳</p><p>Now your designs and implementation are perfectly aligned!</p><p>Hope this helps you achieve consistency between your designs and development. <br>Bye! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddb725e31ffe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Coroutines] Job과 자식 코루틴 기다리기(Kotlin Coroutines 책 요약)]]></title>
            <link>https://medium.com/@seoon53/coroutines-job%EA%B3%BC-%EC%9E%90%EC%8B%9D-%EC%BD%94%EB%A3%A8%ED%8B%B4-%EA%B8%B0%EB%8B%A4%EB%A6%AC%EA%B8%B0-kotlin-coroutines-%EC%B1%85-%EC%9A%94%EC%95%BD-7f077ee76843?source=rss-6d057e5de27c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f077ee76843</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[coroutine-job]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Minseon Cho]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 07:16:43 GMT</pubDate>
            <atom:updated>2024-11-25T06:24:03.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkqWrJmjEFKpVy_H4Eyzfg.jpeg" /></figure><p>안녕하세요! 이번 글에서는 <strong>Kotlin Coroutines</strong> 책의 8장 내용 중 <strong>Job</strong>과 자식 코루틴 기다리기에 대해 요약 및 정리합니다.</p><h3>Job이란?</h3><p>Job은 코루틴의 <strong>취소 및 상태 관리</strong>에 사용되는 중요하고 유용한 컨텍스트입니다.</p><h3>Job의 상태</h3><pre>선택가능한 시작 상태    기본적인 시작 상태         wait children<br>    +-----+ start  +--------+ complete   +-------------+  finish  +-----------+<br>    | New | -----&gt; | Active | ---------&gt; | Completing  | -------&gt; | Completed |<br>    +-----+        +--------+            +-------------+          +-----------+<br>                     |  cancel / fail       |<br>                     |     +----------------+<br>                     |     |<br>                     V     V<br>                 +------------+                           finish  +-----------+<br>                 | Cancelling | --------------------------------&gt; | Cancelled |<br>                 +------------+                                   +-----------+</pre><ul><li><strong>Active</strong> : 이 상태에서 잡은 실행중이며 코루틴은 잡을 수행하고 있습니다. 코루틴 빌더를 사용하여 잡이 생성된 경우, 이 상태에서 코루틴의 본문이 실행됩니다. 대부분의 코루틴은 Active 상태로 시작되며 이 상태에서 자식 코루틴을 시작할 수 있습니다.</li><li><strong>New</strong> : 지연 시작되는 코루틴의 경우 New 상태에서 시작되며 Active 상태가 되려면 작업이 실행되어야 합니다.</li><li><strong>Completing</strong> : 작업의 실행이 완료되면 Completing 상태가 되며 자식들을 기다립니다.</li><li><strong>Completed</strong> : Completing 상태에서 자식들의 실행까지 모두 끝났다면 Completed 상태가 됩니다.</li><li><strong>Cancelling :</strong> 잡이 실행 도중에(Active, Completing 상태일 때) 취소나 실패하게 되면 Cancelling 상태가 됩니다. 여기서 연결을 끊고 자원을 반환하는 등의 후처리 작업을 할 수 있습니다.</li><li><strong>Cancelled :</strong> 후처리 작업이 완료되면 잡은 Cancelled 상태가 됩니다.</li></ul><h3><strong>잡의 상태를 볼 수 있는 방법 — toString 메서드</strong></h3><pre>suspend fun main() = coroutineScope {<br>    val job = Job()<br>    println(job) // JobImpl{Active}@2328c243<br>    job.complete() // 메서드로 완료를 시킬 때까지 Active 상태<br>    println(job) // JobImpl{Completed}@2328c243<br><br>    val activeJob = launch {<br>        delay(100)<br>    }<br>    println(activeJob) // StandaloneCoroutine{Active}@1996cd68<br>    activeJob.join()<br>    println(activeJob) // StandaloneCoroutine{Completed}@1996cd68<br><br>    val lazyJob = launch(start = CoroutineStart.LAZY) {<br>        delay(100)<br>    }<br>    println(lazyJob) // LazyStandaloneCoroutine{New}@ccd0532<br>    lazyJob.start()<br>    println(lazyJob) // LazyStandaloneCoroutine{Active}@ccd0532<br>    lazyJob.join()<br>    println(lazyJob) // LazyStandaloneCoroutine{Completed}@ccd0532<br>}</pre><h3><strong>잡의 상태를 확인할 수 있는 방법 — isActive, isCompleted, isCancelled 프로퍼티</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O39t5Y5LgXy1qgtvnk-nQA.png" /></figure><h3>부모-자식 관계에서의 Job</h3><p><strong>코루틴 빌더는 부모의 잡을 기초로 자신들의 잡을 생성</strong>합니다.</p><p>코틀린 코루틴 라이브러리의 <strong>모든 코루틴 빌더는 자신만의 잡을 생성</strong>하며 대부분의 코루틴 빌더는 잡을 반환합니다. 예로 launch, async 함수를 통해 반환타입이 Job 이라는 사실을 알 수 있습니다.</p><pre>public fun CoroutineScope.launch(<br>    context: CoroutineContext = EmptyCoroutineContext,<br>    start: CoroutineStart = CoroutineStart.DEFAULT,<br>    block: suspend CoroutineScope.() -&gt; Unit<br>): Job { ... } </pre><p>Job은 코루틴이 상속하지 않는 유일한 컨텍스트입니다. 모든 코루틴은 자신만의 Job을 생성하며 <strong>인자 또는 부모 코루틴으로부터 온 Job은 새로운 Job의 부모로 사용</strong>됩니다.</p><pre>fun main(): Unit = runBlocking {<br>    val name = CoroutineName(&quot;Some name&quot;)<br>    val job = Job()</pre><pre>    launch(name + job) {<br>        val childName = coroutineContext[CoroutineName]<br>        println(childName == name) // true<br>        val childJob = coroutineContext.job<br>        println(childJob == job) // false<br>        println(childJob == job.children.first()) // true<br>    }<br>}</pre><blockquote><em>주의해야할 사항은 새로운 Job 컨텍스트가 부모의 잡을 대체하면 부모와 자식간에 아무 관계가 없게되고, 따라서 구조화된 동시성이 작동하지 않게된다는 것입니다. 위 코드에서도 </em><em>runBlocking과 </em><em>launch로 만들어진 코루틴은 부모-자식 관계가 아닙니다. 이런 방식은 골치 아픈 상황이 발생할 수 있기때문에 피하는게 좋습니다.💡</em></blockquote><h3>자식 기다리기</h3><p>Job의 첫번째 중요한 이점은 <strong>코루틴이 완료될 때 까지 기다리는데 사용될 수 있다는 점</strong>입니다. 이를 위해 <strong>join</strong> 메서드를 사용합니다. join 메서드는 지정한 잡이 Completed나 Cancelled와 같은 마지막 상태에 도달할 때 까지 기다리는 중단함수입니다.</p><pre>fun main(): Unit = runBlocking {<br>    launch { // job1<br>        delay(1000)<br>        println(&quot;Test1 done&quot;)<br>    }<br>    launch {// job 2<br>        delay(1000)<br>        println(&quot;Test2 done&quot;)<br>    }</pre><h3>잡 팩토리 함수 Job()</h3><p>Job() 팩토리 함수를 사용하면 코루틴 없이도 Job을 만들 수 있습니다.</p><p>이 팩토리 함수는 언뜻보면 Job의 생성자처럼 보이지만 <strong>생성자 처럼 보이는 함수</strong>입니다.(* Job은 인터페이스이므로 생성자를 가질 수 없습니다)</p><p>그리고 이 함수를 통해 만들어진 잡은 어떤 코루틴과도 연관되지않으며 한개 이상의 자식 코루틴을 가진 부모잡으로 활용할 수 있습니다.</p><blockquote><em>이 Job() 함수를 사용할 때 흔한 실수 중 하나는, 이 함수로 잡을 생성하고 다른 코루틴의 부모로 지정한 뒤에 </em><em>join을 호출하는 것 입니다. 아래 코드 예시를 참고해주세요.</em></blockquote><pre>// 아래 코드는 영원히 종료되지 않는다.<br>suspend fun main(): Unit = coroutineScope {<br>    val job = Job()<br>    launch(job) {<br>        delay(1000)<br>        println(&quot;text1&quot;)<br>    }<br>    launch(job) {<br>        delay(2000)<br>        println(&quot;text2&quot;)<br>    }<br>    job.join() // 여기서 영원히 대기..<br>    println(&quot;will not be printed&quot;) // 출력되지 않음<br>}</pre><p>Job 팩토리 함수가 실제로 반환하는 타입은 Job이 아니라 하위 인터페이스인 CompletableJob 입니다.</p><p>CompletableJob은 아래 두 함수를 추가로 갖고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hp6LjXU2pgY_MNgw8cXbSQ.png" /></figure><h4>complete()</h4><p>complete() 는 잡을 완료하는데 사용됩니다. 이 함수를 사용하면 모든 자식 코루틴의 작업이 완료될때까지 실행된 상태를 유지하지만, complete를 호출한 잡에서 새로운 코루틴이 시작될 수는 없습니다.<br>job이 이 함수호출로 인해 완료되면 true, 그렇지 않을 경우 false를 반환합니다.</p><pre>fun main() = runBlocking {<br>    val job = Job()<br><br>    launch(job) {<br>        repeat(5) { num -&gt;<br>            delay(200)<br>            println(&quot;Rep$num&quot;)<br>        }<br>    }<br><br>    launch {<br>        delay(500)<br>        job.complete()<br>    }<br><br>    job.join()<br><br>    launch(job) {<br>        println(&quot;will not be printed&quot;)<br>    }<br><br>    println(&quot;Done&quot;)<br>}<br><br>// Rep0<br>// Rep1<br>// Rep2<br>// Rep3<br>// Rep4<br>// Done</pre><p>주로 잡의 마지막 코루틴을 시작한 후 사용 됩니다. 이후에는 join 함수를 사용해 잡이 완료되는걸 기다리기만 하면 됩니다.</p><pre>suspend fun main(): Unit = coroutineScope {<br>    val job = Job()<br><br>    launch(job) {<br>        delay(1000)<br>        println(&quot;text1&quot;)<br>    }<br><br>    launch(job) {<br>        delay(2000)<br>        println(&quot;text2&quot;)<br>    }<br>    job.complete()<br>    job.join()<br>}<br>// (1초후)<br>// text1<br>// (1초후)<br>// text2</pre><h4>completeExceptionally(exception: Throwable)</h4><p>completeExceptionally(exception: Throwable)는 인자로 받은 예외로 잡을 완료시킵니다. 모든 자식 코루틴은 주어진 예외를 래핑한 CancellationException으로 취소됩니다. 반환값은 complete 메서드처럼 “잡이 함수의 실행으로 종료되었습니까?” 라는 질문에 대한 응답이 됩니다.</p><pre>fun main() = runBlocking {<br>    val job = Job()<br><br>    launch(job) {<br>        repeat(5) { num -&gt;<br>            delay(200)<br>            println(&quot;Rep$num&quot;)<br>        }<br>    }<br><br>    launch {<br>        delay(500)<br>        job.completeExceptionally(<br>     Error(&quot;Some error&quot;)<br>    )<br>    }<br><br>    job.join()<br><br>    launch(job) {<br>        println(&quot;will not be printed&quot;)<br>    }<br><br>    println(&quot;Done&quot;)<br>}<br><br>// Rep0<br>// Rep1<br>// Done</pre><h3>정리</h3><p>Job은 Kotlin Coroutines에서 중요한 컨텍스트로, 코루틴 상태 관리 및 자식 코루틴 대기를 유연하게 처리할 수 있습니다. 이를 통해 구조화된 동시성을 유지하며 안정적인 비동기 처리를 구현할 수 있습니다.</p><p><strong>읽어주셔서 감사합니다.<br>Happy Coding! 😊</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f077ee76843" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Compose] Changing Lottie Colors in Compose ✨]]></title>
            <link>https://medium.com/@seoon53/compose-changing-lottie-colors-in-compose-0ab49d41b7f7?source=rss-6d057e5de27c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ab49d41b7f7</guid>
            <category><![CDATA[lottie]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[dynamic-property]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[jetpack-compose-tutorial]]></category>
            <dc:creator><![CDATA[Minseon Cho]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 06:55:36 GMT</pubDate>
            <atom:updated>2024-11-25T06:24:26.279Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there! 👋 <br>Today, I’ll share how you can dynamically change the colors of a Lottie animation when using Compose. Let’s dive right in. 🚀</p><h3>The Animation Before Changing Colors</h3><p>Here’s an example of a loading animation. We’ll customize its colors to make it our own. 🎨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*nJFubAA8U3OYBPDFumpfeg.gif" /></figure><h3>The Solution: Dynamic Properties</h3><p>In Jetpack Compose, there’s a Composable function called rememberLottieDynamicProperties. Just from the name, you can tell it’s designed to let you customize Lottie properties dynamically. How convenient is that? 👏</p><p>Here’s what the function looks like:</p><pre>/**<br> * Use this function when you want to apply one or more dynamic properties to an animation.<br> * This takes a vararg of individual dynamic properties which should be created with [rememberLottieDynamicProperty].<br> *<br> * @see rememberLottieDynamicProperty<br> * @see LottieDrawable.setMaintainOriginalImageBounds<br> */<br>@Composable<br>fun rememberLottieDynamicProperties(<br>    vararg properties: LottieDynamicProperty&lt;*&gt;,<br>): LottieDynamicProperties {<br>    return remember(properties.contentHashCode()) {<br>        LottieDynamicProperties(properties.toList())<br>    }<br>}</pre><p>It accepts parameters using vararg, which means you can pass multiple dynamicProperty values. The properties you pass are created using the rememberLottieDynamicProperty function, as mentioned in the documentation.</p><h3>The rememberLottieDynamicProperty Function</h3><pre>/**<br> * Use this to create a single dynamic property for an animation.<br> *<br> * @param property should be one of [com.airbnb.lottie.LottieProperty].<br> * @param value the desired value to use as this property&#39;s value.<br> * @param keyPath the string parts of a [com.airbnb.lottie.model.KeyPath] that specify which animation element<br> *                the property resides on.<br> */<br>@Composable<br>fun &lt;T&gt; rememberLottieDynamicProperty(<br>    property: T,<br>    value: T,<br>    vararg keyPath: String,<br>): LottieDynamicProperty&lt;T&gt; {<br>    val keyPathObj = remember(keyPath) { KeyPath(*keyPath) }<br>    return remember(keyPathObj, property, value) {<br>        LottieDynamicProperty(property, keyPathObj, value)<br>    }<br>}<br><br>/**<br> * Use this to create a single dynamic property for an animation.<br> *<br> * @param property Should be one of [com.airbnb.lottie.LottieProperty].<br> * @param keyPath The string parts of a [com.airbnb.lottie.model.KeyPath] that specify which animation element<br> *                the property resides on.<br> * @param callback A callback that will be invoked during the drawing pass with current frame info. The frame<br> *                 info can be used to alter the property&#39;s value based on the original animation data or it<br> *                 can be completely ignored and an arbitrary value can be returned. In this case, you may want<br> *                 the overloaded version of this function that takes a static value instead of a callback.<br> */<br>@Composable<br>fun &lt;T&gt; rememberLottieDynamicProperty(<br>    property: T,<br>    vararg keyPath: String,<br>    callback: (frameInfo: LottieFrameInfo&lt;T&gt;) -&gt; T,<br>): LottieDynamicProperty&lt;T&gt; {<br>    val keyPathObj = remember(keyPath.contentHashCode()) { KeyPath(*keyPath) }<br>    val callbackState by rememberUpdatedState(callback)<br>    return remember(keyPathObj, property) {<br>        LottieDynamicProperty(<br>            property,<br>            keyPathObj,<br>        ) { callbackState(it) }<br>    }<br>}</pre><h4>Breaking Down the Parameters</h4><p>Here’s a quick summary of what each parameter does:</p><ul><li><strong>property</strong>: The attribute you want to modify. It must be one of the constants defined in LottieProperty.</li><li><strong>value</strong>: The new value to assign to the property.<br>Example: COLOR_FILTER requires a ColorFilter, while OPACITY expects an Integer (0–100).</li><li><strong>keyPath</strong>: Specifies the animation element to target.</li><li><strong>callback</strong>: Provides dynamic values for each frame.</li></ul><p>For today’s example, since we’re changing the overall color of the Lottie animation, we’ll use the COLOR_FILTER property. This makes it easy to adjust the colors of the entire animation dynamically. 🎨</p><p>Here’s what I did step-by-step:</p><h3>Step 1: Setting Up the Dynamic Properties</h3><pre>val dynamicProperties = rememberLottieDynamicProperties(<br>    rememberLottieDynamicProperty(<br>        property = LottieProperty.COLOR_FILTER,<br>        value = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(<br>            MainBlue.hashCode(),<br>            BlendModeCompat.SRC_ATOP<br>        ),<br>        keyPath = arrayOf(&quot;**&quot;) // Apply to all layers and objects<br>    )<br>)</pre><ul><li>We passed LottieProperty.COLOR_FILTER to property.</li><li>For value, we created a ColorFilter using our predefined MainBlue color with the SRC_ATOP mode.</li><li>The keyPath is set to **, meaning the color filter applies to all layers and objects.</li></ul><h3>Step 2: Applying the Dynamic Property</h3><pre>val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.loading))<br><br>LottieAnimation(<br>    composition = composition,<br>    iterations = LottieConstants.IterateForever,<br>    dynamicProperties = dynamicProperties<br>)</pre><p>Finally, pass the dynamicProperties to the LottieAnimation composable like this.</p><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*laDiZCKbJp4xjN_fXxfJBw.gif" /></figure><p>And voilà! The animation now has a fresh new look with the color changes. 🎉</p><h3>Customizing Beyond Colors</h3><p>You’re not limited to colors. Explore the constants in LottieProperty to discover other customizable elements. Who knows what amazing animations you’ll create? 😊</p><p>That’s it for today. Happy coding! 🚀</p><p>Let me know if you’d like to tweak the tone further or add more examples! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ab49d41b7f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Compose] Displaying a Tooltip at a Specific Location — onGloballyPositioned]]></title>
            <link>https://medium.com/@seoon53/compose-displaying-a-tooltip-at-a-specific-location-ongloballypositioned-010eadf632cf?source=rss-6d057e5de27c------2</link>
            <guid isPermaLink="false">https://medium.com/p/010eadf632cf</guid>
            <category><![CDATA[ongloballypositioned]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose-tutorial]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Minseon Cho]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 13:26:58 GMT</pubDate>
            <atom:updated>2024-11-25T06:24:42.691Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Compose] Displaying a Tooltip at a Specific Location — <em>onGloballyPositioned</em></h3><p>Hi there! During a recent project, I came across a requirement to show a tooltip at a specific location on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*05iUWxDSPfL_rX1tcmRroA.jpeg" /></figure><h3>The Requirement</h3><p>I needed to display a tooltip just below the checkbox in the first item of a LazyGrid. To achieve this, I had to determine the exact position of the checkbox.</p><h3>The Solution: onGloballyPositioned</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1ows8PLvmXg6WizSf11iA.jpeg" /></figure><p>Jetpack Compose offers a handy modifier called onGloballyPositioned, which you can use whenever you need information about the global position of a composable.</p><h4>What does onGloballyPositioned do?</h4><p>This modifier provides a callback with the composable’s LayoutCoordinates whenever its global position changes. It’s triggered after the composition is complete and the coordinates are finalized. This makes it super helpful for scenarios like mine!</p><p>For my requirement, I attached this modifier to the checkbox in the first item. Once I got its position, I calculated the final coordinates for the tooltip, considering the design specifications.</p><h3>Implementation Steps</h3><p>Here’s how I approached it step by step:</p><ol><li><strong>Track the Tooltip’s Position:</strong><br>I created a MutableState to store the tooltip’s offset.</li></ol><pre>var guideTooltipOffset by remember { mutableStateOf(Offset.Zero) }</pre><p><strong>2. Calculate the Offset:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zw4BqmYps-8vZQkE9Iuf5Q.png" /></figure><p>I used a lambda onFirstItemCheckboxPositioned to process the checkbox’s layout coordinates when onGloballyPositioned was triggered.</p><p>Here, we actually calculate the layout coordinates to expose the tooltip.</p><pre>val onFirstItemCheckboxPositioned: (LayoutCoordinates) -&gt; Unit = {<br>    val checkboxBottomCenterOffset = it.boundsInParent().bottomCenter<br>    guideTooltipOffset = Offset(<br>        x = checkboxBottomCenterOffset.x - bubbleToTailTipDistance,<br>        y = checkboxBottomCenterOffset.y + checkboxToTailTipDistance<br>    )<br>}</pre><p><strong>3. Attach the Modifier:</strong><br>This lambda was passed down to the checkbox in the first item of my LazyGrid.</p><pre>RounzMirrorCircleCheckbox(<br>    modifier = Modifier<br>        .onGloballyPositioned { onFirstItemCheckboxPositioned(it) }<br>)</pre><p><strong>4. Position the Tooltip:</strong><br>Finally, I used the calculated guideTooltipOffset to position the tooltip in the UI.</p><pre>GuideTooltip(<br>    modifier = Modifier.padding(<br>        start = guideTooltipOffset.x.pxToDp(),<br>        top = guideTooltipOffset.y.pxToDp()<br>    )<br>)</pre><h3>Bonus: Different bounds...() Functions</h3><p>While implementing this, I learned about the various LayoutCoordinates functions like:</p><ul><li><strong>boundsInParent()</strong> — Coordinates within the composable&#39;s immediate parent.</li><li><strong>boundsInRoot()</strong> — Coordinates within the Compose root.</li><li><strong>boundsInWindow()</strong> — Coordinates within the window.</li></ul><p>These provide great flexibility depending on the scope of your layout.</p><h3>The Final Flow</h3><p>Here’s the overall sequence:</p><ol><li>The checkbox in the first item triggers onGloballyPositioned once its coordinates are finalized.</li><li>The lambda calculates the tooltip’s position based on the checkbox’s layout.</li><li>The tooltip is displayed at the calculated coordinates.</li></ol><h3>Wrap-Up</h3><p>The onGloballyPositioned modifier is super handy for positioning tooltips or popups dynamically in Compose. I hope this example helps you use it effectively in your projects too!</p><p>Thanks for reading! 😊</p><p>Let me know if you need further refinements!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=010eadf632cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Compose] BottomSheetScaffold Hidden 상태 대신 PartiallyExpanded 만 감지되는 이슈]]></title>
            <link>https://medium.com/@seoon53/compose-bottomsheetscaffold-hidden-%EC%83%81%ED%83%9C-%EB%8C%80%EC%8B%A0-partiallyexpanded-%EB%A7%8C-%EA%B0%90%EC%A7%80%EB%90%98%EB%8A%94-%EC%9D%B4%EC%8A%88-761d8ca18399?source=rss-6d057e5de27c------2</link>
            <guid isPermaLink="false">https://medium.com/p/761d8ca18399</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[bottomsheetscaffold]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[bottomsheet]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Minseon Cho]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 13:14:31 GMT</pubDate>
            <atom:updated>2024-11-25T06:24:56.974Z</atom:updated>
            <content:encoded><![CDATA[<p>오늘은<br>BottomSheetScaffold 로 기본 Hidden 상태의 바텀시트를 구현했을 때 Hidden 상태를 감지할 수 없는 이슈를 경험해서 공유해보려고 합니다.</p><pre>val bottomSheetScaffoldState = rememberBottomSheetScaffoldState(<br>    bottomSheetState = rememberStandardBottomSheetState(<br>       initialValue = SheetValue.Hidden,<br>       skipHiddenState = false<br>    )<br>)<br><br>BottomSheetScaffold(<br>    modifier = Modifier,<br>    scaffoldState = bottomSheetScaffoldState,<br>    sheetMaxWidth = deviceWidthDp.dp,<br>    sheetShape = RoundedCornerShape(20.pxToDp()),<br>    sheetContent = {<br>       // content<br>    }, sheetDragHandle = {<br>       // custom drag handle <br>    }, sheetPeekHeight = 0.dp<br>) {</pre><p>이런식으로 기본적으로 숨겨져있는 바텀시트를 만들기 위해 bottomSheet 상태에 initialValue = SheetValue.Hidden 를 설정했습니다. <br>또, sheetPeekHeight를 0으로 둬서 닫혀있을 때도 화면에서 완전히 숨기고 싶었습니다.</p><p>이렇게 바텀시트를 설정해놓고<br>저는 바텀시트가 Hidden 상태가 아닐 때를 감지해서 어떤 컴포저블을 노출해주고 싶었습니다.<br>그래서 아래와 같이 Hidden 상태가 아닐 때 컴포저블 함수를 부르도록 구현했었죠.</p><pre>if (bottomSheetScaffoldState.bottomSheetState.currentValue != SheetValue.Hidden) {<br>    // 컴포저블 함수<br>}</pre><p>위 코드처럼요.</p><p>그런데 제 예상처럼 동작하지 않았습니다.</p><p>디버깅을 해보니 이유는<br>바텀시트의 상태가 Hidden 이 되는 경우가 없어서였습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1m_48Jj6urB4H9jomzUmQ.png" /></figure><p>바텀시트는 위의 SheetValue에 있는 3가지 상태를 가질 수 있는데요. 제가 구현한 바텀시트는 Expanded와 PartiallyExpanded 상태만 가지는걸 확인했습니다.</p><p>처음엔 의아했습니다. 왜 초기 상태를 Hidden으로 주고, bottomSheetScaffoldState.bottomSheetState.hide 함수를 사용해서 숨기기도 했는데 Hidden 상태가 아닌거지? 하구요.</p><p>이리저리 코드를 바꾸며 확인해본결과 sheetPeekHeight 에 0dp 대신 다른 값을 넣자 hide 함수를 불렀을 때 Hidden 상태가 되는 걸 확인할 수 있었습니다. 물론 바텀시트가 만들어진 초기 상태도요.</p><p>1dp 만 줘도 바텀시트는 Hidden 상태가 됐습니다.</p><p>BottomSheetScaffold로 Hidden 상태를 갖는 바텀시트를 만들고싶다면, sheetPeekHeight를 0 이상 주어야함을 주의해야겠습니다.</p><p>😇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=761d8ca18399" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Compose] BottomSheetScaffold 에 scrim 영역 추가하기 with 성능 최적화 — derivedStateOf, drawBehind]]></title>
            <link>https://medium.com/@seoon53/compose-bottomsheetscaffold-%EC%97%90-scrim-%EC%98%81%EC%97%AD-%EC%B6%94%EA%B0%80%ED%95%98%EA%B8%B0-with-%EC%84%B1%EB%8A%A5-%EC%B5%9C%EC%A0%81%ED%99%94-derivedstateof-drawbehind-72ecbe412e56?source=rss-6d057e5de27c------2</link>
            <guid isPermaLink="false">https://medium.com/p/72ecbe412e56</guid>
            <category><![CDATA[modalbottomsheet]]></category>
            <category><![CDATA[derivedstateof]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[bottomsheetscaffold]]></category>
            <dc:creator><![CDATA[Minseon Cho]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 06:43:05 GMT</pubDate>
            <atom:updated>2024-11-25T06:25:08.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Compose] BottomSheetScaffold 에 scrim 영역 추가하기 with 성능 최적화 — derivedStateOf, drawBehind</h3><p>개발 중 바텀시트에 Webview 로 특정 html을 로드해서 보여줘야하는 요구사항이 있었습니다.</p><p>Compose에 아직 익숙하지 않았기에 Compose로는 Bottom sheet 을 어떻게 구현하는지 부터 알아봤었는데요.</p><p>구현 방법은 두 가지로, BottomSheetScaffold와 ModalBottmSheet가 있었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-9JhRsoPqwlww-bD6qhIcg.png" /><figcaption>bottom sheet 요소 설명</figcaption></figure><p>저는 요구사항에 bottom sheet의 scrim 영역이 어둡게 처리되고 클릭하면 닫혀야했기에 처음엔 이 기능이 이미 구현된 ModalBottomSheet로 구현했습니다.</p><p>하지만 결과가 썩 만족스럽지는 않았는데요.</p><p>이유는 ModalBottmSheet는 특성 상 불릴때마다 새로 만들어져서 bottom sheet가 올라올 때 흰 화면이 살짝씩 보이기 때문이었습니다. 아마 Webview 때문에 쓰고있던 AndroidView의 영향도 있었던 거 같습니다.</p><p>그래서 ModalBottomSheet로 구현한 내용을 BottomSheetScaffold로 바꿔봤습니다. <br>BottomSheetScaffold로 구현 방법을 변경해본 결과, <br>문제였던 흰 화면이 보이는 현상은 없어졌습니다. BottomSheetScaffold는 sheet를 항상 ui tree에 유지하고 있기 때문입니다. 즉, bottom sheet를 보여줄 때 마다 새로 composition 되는게 아닌거죠.</p><p>이렇게 bottom sheet 동작 자체는 개선이 됐으나 bottom sheet의 scrim 영역이 없었기에 이를 구현해주어야 했습니다.</p><p>구현은 bottom sheet 뒤에 화면 전체를 덮는 Box를 하나 만들고 이 Box의 background alpha 값을 bottom sheet의 높이에 따라 업데이트 시켜주는 방향으로 구현했습니다.</p><blockquote>compose animation api 중 animatedFloatAsState를 사용했는데 배경지식이 없는 분들은 <a href="https://medium.com/@seoon53/compose-5-quick-animations-to-make-your-app-stand-out-video-%EC%9A%94%EC%95%BD-51811e601e68">이 글</a>을 읽어보면 좋을 것 같습니다.😁</blockquote><p>먼저<br>background alpha 설정에 쓰일 상태 변수를 하나 만들겠습니다.</p><pre>var bottomSheetScrimAlpha by remember { mutableFloatStateOf(0f) }</pre><p>다음으로는<br>bottom sheet의 offset을 알 수 있어야 합니다. 그리고 이 offset 이 변경됨에 따라 bottomSheetScrimAlpha 값을 업데이트 시켜주어야 하겠죠</p><pre>val bottomSheetScaffoldState = rememberBottomSheetScaffoldState(<br>    bottomSheetState = rememberStandardBottomSheetState(<br>        initialValue = SheetValue.Hidden,<br>        skipHiddenState = false<br>    )<br>)<br><br>bottomSheetScaffoldState.bottomSheetState.requireOffset()</pre><p>offset 은 위 코드 처럼 requireOffset을 통해 가져올 수 있습니다. <br>여기서 주의할 점이 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nw9uUzTnYROn4NS9SWk4RA.png" /></figure><p>위 requireOffset의 docs를 보면<br>“첫번째 컴포지션 중에는 IllegalStateException이 발생한다” 라고 적혀있습니다. <br>그렇기 때문에 저는 requireOffset을 BottomSheetScaffold의 <em>drawBehind </em>수정자에서 부르도록 구현했습니다.</p><p>Compose에는 세가지 단계가 존재한다는걸 아실겁니다. <br>Composition, Layout, Draw 인데요.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQ4vYoXSjTldeMBJRvkw-g.png" /></figure><p>drawBehind는 draw 단계에서 불립니다. 즉 Composition이 모두 끝난 후 불린다는 거죠.<br>따라서 drawBehind 안에서 requireOffset를 사용한다면 IllegalStateException을 만나지 않을 수 있습니다.</p><pre>BottomSheetScaffold(<br>    modifier = Modifier<br>        .drawBehind {<br>            val offset = bottomSheetScaffoldState.bottomSheetState.requireOffset() // 바텀시트 현재 오프셋 값<br>            val bottomSheetMinOffset = deviceHeightInPx - bottomSheetContentHeightInPx - bottomSheetDragHandleHeightInPx // 바텀시트가 가질 수 있는 최소 offset 값<br>            bottomSheetScrimAlpha = ((deviceHeightInPx - offset) / (deviceHeightInPx - bottomSheetMinOffset)).coerceIn(0f, 1f) * 0.7f<br>        },</pre><p>코드로 보면 이렇습니다.<br>1. requireOffset로 현재 offset을 가져옵니다.<br>2. bottomSheetMinOffset 은 bottom sheet가 최대로 올라왔을 때의 offset 값입니다. offset은 바텀시트의 y 값이기 때문에 내려가있을 때 최대값을 갖고 완전히 펼쳐졌을 때 최소값을 가집니다.<br>3. 디자인 요구사항에서 scrim은 0~0.7 사이의 값을 가져야하기에 offset과 bottom sheet의 높이를 사용해서 alpha 값을 계산해줍니다.</p><p>이렇게 bottomSheetScrimAlpha를 업데이트 시켜주니 이를 적용시켜줄 컴포저블이 필요합니다.</p><pre>Box( // bottomSheet scrim 영역 구현을 위한 Box<br>    modifier = Modifier<br>        .fillMaxSize()<br>        .drawBehind {<br>            drawRect(Black.copy(alpha = bottomSheetScrimAlpha))<br>        }<br>        .clickable(<br>            indication = null,<br>            interactionSource = remember { MutableInteractionSource() }<br>        ) {<br>            viewModel.onBottomSheetScrimClicked()<br>        }<br>)</pre><p>scrim 역할을 할 Box를 하나 만들었습니다. Surface나 다른 컴포저블 대신 Box를 사용한 이유는 modifier 설정 이외에 다른 content가 필요없기 때문입니다. Box 컴포저블 함수 중 content를 받지 않는 함수가 있어 이런 경우 주로 Box를 사용하는 편입니다. 😁</p><p>그리고 Box의 drawBehind에서 drawRect를 통해 투명도가 적용된 검은색을 그리도록 구현했습니다.<br>왜 background(color = Black.copy(alpha = bottomSheetScrimAlpha))이렇게 background Modifier를 사용하지 않았는지 궁금하실 수 있는데요.</p><p>이유는 <br>bottomSheetScrimAlpha 값은 굉장히 자주 바뀌는 값입니다. background 수정자에 이렇게 자주 바뀌는 값을 적용하면 값이 바뀔 때 마다 recomposition이 발생됩니다. <br>이에 비해 drawBehind를 사용하면 Draw 단계에서 alpha 값을 바꿔서 그리기만 하기 때문에 recomposition이 발생하지 않습니다. <br>이는 background와 달리 drawBehind는 onDraw라는 람다를 받기 때문입니다. 람다 안에서 참조하는 값이 자주 바뀌기는 하지만 람다 객체 자체가 변경되진 않기때문에 composition 입장에서 봤을 땐 바뀐게 없는거죠. 즉 recomposition이 필요하다고 판단하지 않습니다.<br>그렇기 때문에 Modifier를 사용할 때 불필요한 recomposition을 줄이고싶다면 사용하고자 하는 Modifier가 람다를 받는 버전의 함수가 있는지 살펴보면 좋습니다.</p><p>그리고 scrim 영역 클릭 시 bottomSheet가 닫히는 동작을 구현하기 위해 클릭 시 viewModel.onBottomSheetScrimClicked를 부르고 내부에서 bottom sheet를 닫는 동작을 트리거하도록 구현했습니다. 이 부분은 각자 구조에 맞게 구현하면 되기에 굳이 코드 첨부는 하지 않겠습니다.</p><p>이제 마지막으로<br>scrim 역할을 하는 Box의 visibility를 관리할 상태가 하나 필요합니다. bottomSheetScrimAlpha가 0 이상이면 보이고, 0보다 같거나 작으면 숨겨주는 방식으로 구현해보겠습니다.</p><pre>val isBottomSheetScrimVisible by remember {<br>    derivedStateOf {<br>        bottomSheetScrimAlpha &gt; 0<br>    }<br>}<br><br>if (isBottomSheetScrimVisible) {<br>    Box( // bottomSheet scrim 영역 구현을 위한 Box<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .drawBehind {<br>                drawRect(Black.copy(alpha = bottomSheetScrimAlpha))<br>            }<br>            .clickable(<br>                indication = null,<br>                interactionSource = remember { MutableInteractionSource() }<br>            ) {<br>                viewModel.onBottomSheetScrimClicked()<br>            }<br>    )<br>}</pre><p>그럼 최종적으로 위와 같이 구현됩니다. <br>여기서 제가 isBottomSheetScrimVisible를 계산하는데 derivedStateOf를 사용했는데요. 이것도 불필요한 recomposition을 막기 위함입니다.</p><p>derivedStateOf 를 사용하면 상태를 계산할 때 사용하는 값이 자주 변경되더라도 상태 자체가 불필요하게 자주 업데이트되는 것을 방지할 수 있습니다.<br>isBottomSheetScrimVisible은 bottomSheetScrimAlpha 값을 기반으로 상태를 계산합니다. 이 상태는 다음 두 조건에서만 업데이트가 필요합니다.</p><ol><li>bottomSheetScrimAlpha가 <strong>0보다 커질 때</strong></li><li>bottomSheetScrimAlpha가 <strong>0보다 작거나 같아질 때</strong></li></ol><p>그런데 derivedStateOf를 사용하지 않으면 bottomSheetScrimAlpha가 변경될 때마다 isBottomSheetScrimVisible 상태가 업데이트됩니다. 이는 derivedStateOf를 사용함으로써 위 조건 1번/2번에 해당할 때만 상태를 업데이트 하도록 제한할 수 있습니다. <br>derivedStateOf는상태를 계산한 값이 이전 값과 다를 때만 업데이트하기 때문입니다.</p><p>derivedStateOf 는 이렇게 상태를 계산하는 횟수에 비해 상태를 업데이트하는 횟수가 적을 때 유용하게 사용됩니다. 상태를 계산하는 만큼 업데이트하는 경우라면 오히려 불필요한 오버헤드가 있을 수 있으니 필요한 경우에만 사용하면 좋겠습니다.</p><h3>최종 코드</h3><pre>val bottomSheetScaffoldState = rememberBottomSheetScaffoldState(<br>    bottomSheetState = rememberStandardBottomSheetState(<br>        initialValue = SheetValue.Hidden,<br>        skipHiddenState = false<br>    )<br>)<br>var bottomSheetScrimAlpha by remember { mutableFloatStateOf(0f) }<br>val isBottomSheetScrimVisible by remember {<br>    derivedStateOf {<br>        bottomSheetScrimAlpha &gt; 0<br>    }<br>}<br><br>BottomSheetScaffold(<br>    modifier = Modifier<br>        .drawBehind {<br>            val offset = bottomSheetScaffoldState.bottomSheetState.requireOffset() // 바텀시트 현재 오프셋 값<br>            val bottomSheetMinOffset = deviceHeightInPx - bottomSheetContentHeightInPx - bottomSheetDragHand<br>            bottomSheetScrimAlpha = ((deviceHeightInPx - offset) / (deviceHeightInPx - bottomSheetMinOffset)<br>        },<br>    scaffoldState = bottomSheetScaffoldState,<br>    sheetMaxWidth = deviceWidthDp.dp,<br>    sheetShape = RoundedCornerShape(20.pxToDp()),<br>    sheetContent = {<br>        // bottom sheet content 구현 내용<br>    }, sheetDragHandle = {<br>        // drag handle 커스텀 구현 내용<br>    }, sheetPeekHeight = 0.dp<br>) {<br>    Column(<br>        modifier = modifier<br>            .fillMaxSize()<br>            .background(White)<br>            .then(detectPointerReleased)<br>    ) {<br>        // content 구현 내용<br>    }<br><br>    if (isBottomSheetScrimVisible) {<br>        Box( // bottomSheet scrim 영역 구현을 위한 Box<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .drawBehind {<br>                    drawRect(Black.copy(alpha = bottomSheetScrimAlpha))<br>                }<br>                .clickable(<br>                    indication = null,<br>                    interactionSource = remember { MutableInteractionSource() }<br>                ) {<br>                    viewModel.onBottomSheetScrimClicked()<br>                }<br>        )<br>    }<br>}</pre><h3>구현 결과</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*AkeQ-u0KiLglEVhNq3ezlQ.gif" /></figure><p>비슷한 상황에 도움이 됐으면 좋겠네요.<br>읽어주셔서 감사합니다! 🏋️‍♀️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72ecbe412e56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Compose] Compose Lottie 색상 바꾸기 — Change Lottie Colors in Compose]]></title>
            <link>https://medium.com/@seoon53/compose-compose-lottie-%EC%83%89%EC%83%81-%EB%B0%94%EA%BE%B8%EA%B8%B0-change-lottie-colors-in-compose-23e25620a066?source=rss-6d057e5de27c------2</link>
            <guid isPermaLink="false">https://medium.com/p/23e25620a066</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[lottie]]></category>
            <dc:creator><![CDATA[Minseon Cho]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 08:25:05 GMT</pubDate>
            <atom:updated>2024-11-25T06:25:19.679Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Compose] Compose Lottie 색상 바꾸기 — Change Lottie Colors in Compose</h3><p>오늘은 Compose에서 lottie 를 사용할 때<br>코드에서 lottie 색상을 변경하는 법을 공유하려고 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*nJFubAA8U3OYBPDFumpfeg.gif" /><figcaption>색상 변경 전 lottie</figcaption></figure><p>위 로딩 lottie 애니메이션의 색을 변경해보겠습니다.</p><p>Compose lottie에는<br>rememberLottieDynamicProperties 라는 Composable 함수가 존재합니다. 이름만 봐도 lottie 속성들을 커스텀할 수 있을 것 같다는 느낌이 옵니다👏</p><pre>/**<br> * Use this function when you want to apply one or more dynamic properties to an animation.<br> * This takes a vararg of individual dynamic properties which should be created with [rememberLottieDynamicProperty].<br> *<br> * @see rememberLottieDynamicProperty<br> * @see LottieDrawable.setMaintainOriginalImageBounds<br> */<br>@Composable<br>fun rememberLottieDynamicProperties(<br>    vararg properties: LottieDynamicProperty&lt;*&gt;,<br>): LottieDynamicProperties {<br>    return remember(properties.contentHashCode()) {<br>        LottieDynamicProperties(properties.toList())<br>    }<br>}</pre><p>rememberLottieDynamicProperties 는 이렇게 생겼습니다.<br>vararg 로 파라미터를 받고 있기 때문에 여러개의 dynamicProperty를 넘길 수 있겠네요.</p><p>넘기는 property는 docs 에 멘션되어있는 rememberLottieDynamicProperty 로 만들면 됩니다.</p><pre>/**<br> * Use this to create a single dynamic property for an animation.<br> *<br> * @param property should be one of [com.airbnb.lottie.LottieProperty].<br> * @param value the desired value to use as this property&#39;s value.<br> * @param keyPath the string parts of a [com.airbnb.lottie.model.KeyPath] that specify which animation element<br> *                the property resides on.<br> */<br>@Composable<br>fun &lt;T&gt; rememberLottieDynamicProperty(<br>    property: T,<br>    value: T,<br>    vararg keyPath: String,<br>): LottieDynamicProperty&lt;T&gt; {<br>    val keyPathObj = remember(keyPath) { KeyPath(*keyPath) }<br>    return remember(keyPathObj, property, value) {<br>        LottieDynamicProperty(property, keyPathObj, value)<br>    }<br>}<br><br>/**<br> * Use this to create a single dynamic property for an animation.<br> *<br> * @param property Should be one of [com.airbnb.lottie.LottieProperty].<br> * @param keyPath The string parts of a [com.airbnb.lottie.model.KeyPath] that specify which animation element<br> *                the property resides on.<br> * @param callback A callback that will be invoked during the drawing pass with current frame info. The frame<br> *                 info can be used to alter the property&#39;s value based on the original animation data or it<br> *                 can be completely ignored and an arbitrary value can be returned. In this case, you may want<br> *                 the overloaded version of this function that takes a static value instead of a callback.<br> */<br>@Composable<br>fun &lt;T&gt; rememberLottieDynamicProperty(<br>    property: T,<br>    vararg keyPath: String,<br>    callback: (frameInfo: LottieFrameInfo&lt;T&gt;) -&gt; T,<br>): LottieDynamicProperty&lt;T&gt; {<br>    val keyPathObj = remember(keyPath.contentHashCode()) { KeyPath(*keyPath) }<br>    val callbackState by rememberUpdatedState(callback)<br>    return remember(keyPathObj, property) {<br>        LottieDynamicProperty(<br>            property,<br>            keyPathObj,<br>        ) { callbackState(it) }<br>    }<br>}</pre><p>각 파라미터에 대한 설명입니다.</p><ul><li>property : 변경하려는 항목을 나타내는 LottieProperty 안에 정의된 상수.</li><li>value : 위 property 에 설정한 속성에 적용할 값<br>property 에 넘긴 상수의 각 타입은 lottie 를 업데이트 하기 위해 설정해야하는 value의 타입입니다. <em><br></em>ColorFilter <em>COLOR_FILTER </em>= new ColorFilter();<br> Integer <em>OPACITY </em>= 4;<br>예로 COLOR_FILTER 의 타입은 ColorFilter이며 OPACITY는 Integer타입으로 0–100 사이의 값을 받습니다.</li><li>keyPath : 변경하려는 속성을 가진 애니메이션 노드로 가는 경로</li><li>callback : 각 프레임에서 호출되며, 업데이트할 때 까지 각 프레임에서 반환되는 단일 값을 알 수 있습니다.</li></ul><p>오늘은 로띠의 전체적인 색상을 바꿀 거기 때문에 COLOR_FILTER 속성을 사용해보겠습니다.</p><pre><br>    val dynamicProperties = rememberLottieDynamicProperties(<br>        rememberLottieDynamicProperty(<br>            property = LottieProperty.COLOR_FILTER,<br>            value = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(<br>                MainBlue.hashCode(),<br>                BlendModeCompat.SRC_ATOP<br>            ),<br>            keyPath = arrayOf(<br>                &quot;**&quot;<br>            )<br>        )<br>    )</pre><p>COLOR_FILTER를 사용해서 dynamicProperty를 만든 코드입니다.</p><p>property에 LottieProperty.COLOR_FILTER를 넘겨줬고, value에 ColorFilter 객체를 넘겨줬습니다.<br>ColorFilter 객체에는 미리 정의해놓은 MainBlue 색상과 SRC_ATOP 설정으로 파란색을 덮어씌우도록 설정했습니다.</p><p>keyPath 에는 필터를 적용할 대상을 지정해야하는데 arrayOf(“**”)는 lottie의 모든 레이어, 모든 객체에 적용하겠다는 의미입니다.</p><p>이렇게 만든 dynamicProperties 변수를</p><pre>val composition by rememberLottieComposition(<br>    LottieCompositionSpec.RawRes(R.raw.loading)<br>)<br>val dynamicProperties = // dynamicProperties 정의<br><br>LottieAnimation(<br>    composition = composition,<br>    iterations = LottieConstants.IterateForever,<br>    dynamicProperties = dynamicProperties<br>)</pre><p>이렇게 LottieAnimation의 dynamicProperties 파라미터에 넘겨주면 색상 변경이 됩니다.</p><p>결과는 아래와 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*laDiZCKbJp4xjN_fXxfJBw.gif" /></figure><p>색상 외에도 lottie를 코드로 커스텀해야할 일이 생기면 LottieProperty 내부에 어떤 값이 정의되어있는지 확인해보면 커스텀 할 수 있는 요소인지를 확인하는데 도움이 될 것 같습니다.</p><p>감사합니다! 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23e25620a066" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Compose] 컴포저블의 위치 알기 — onGloballyPositioned]]></title>
            <link>https://medium.com/@seoon53/compose-%EC%BB%B4%ED%8F%AC%EC%A0%80%EB%B8%94%EC%9D%98-%EC%9C%84%EC%B9%98-%EC%95%8C%EA%B8%B0-ongloballypositioned-43f408d57c1b?source=rss-6d057e5de27c------2</link>
            <guid isPermaLink="false">https://medium.com/p/43f408d57c1b</guid>
            <category><![CDATA[ongloballypositioned]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Minseon Cho]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 06:21:23 GMT</pubDate>
            <atom:updated>2024-11-03T15:11:21.716Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Compose] 컴포저블 위치 알아내어 툴팁 노출하기— onGloballyPositioned</h3><p>개발 중 화면의 특정 위치에 툴팁을 노출해야하는 요구사항이 있었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*qAt13YRTn0sxRhNAiaRivQ.png" /><figcaption>요구사항 참고 이미지</figcaption></figure><p>특정 위치는 LazyGrid 첫번째 아이템의 체크박스 하단이었는데요, 때문에 첫번째 체크박스가 어디에 위치했는지 알아야했습니다.</p><p>Compose에서는 onGloballyPositioned 라는 컴포저블의 위치 정보가 필요할 때 사용할 수 있는 Modifier 수정자가 있는데요. 이걸 사용해서 체크박스 위치를 알아내 하단에 툴팁을 노출해보겠습니다.🫠</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6C25CcKtXSZyZTHVfX05_w.png" /></figure><p>먼저 onGloballyPositioned는,</p><p>컴포저블의 전역적인 위치가 변경될 때 해당 요소의 LayoutCoordinates와 함께 onGloballyPositioned를 호출합니다.</p><p><strong>Composition이 끝나고 좌표가 확정된 후 호출되는 것이죠.</strong></p><p>따라서 위치를 알고싶은 컴포저블의 modifier에 이 수정자를 설정해주면, 컴포저블을 배치할 좌표가 확정됐을 때 콜백을 받을 수 있습니다!</p><p>제 요구사항의 경우에는 첫 번째 아이템의 CheckBox에 해당 수정자를 설정해주어야 합니다.</p><p>그렇게 Checkbox 위치를 알게되면,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBK_Y7zOggac-pTauRP6HA.png" /><figcaption>알아야 하는 좌표 위치 참고 이미지</figcaption></figure><p>여기에 툴팁의 디자인을 참고하여 offset 을 더하고 빼 최종적으로 위 이미지에 표시된 위치의 좌표(실제 툴팁을 배치해야할 좌표)를 계산해서 이 위치에 툴팁을 노출하면 되는거죠.</p><p>코드로 보면,</p><pre>var guideTooltipOffset by remember { mutableStateOf(Offset.Zero) }<br>val onFirstItemCheckboxPositioned: (LayoutCoordinates) -&gt; Unit = {<br>    val checkboxBottomCenterOffsetInItem = it.boundsInParent().bottomCenter // 리스트 아이템 안에서의 체크박스 하단 가운데 offset<br>    val checkboxBottomCenterOffset = ...<br>    guideTooltipOffset = Offset(<br>        x = checkboxBottomCenterOffset.x - bubbleToTailTipDistance,<br>        y = checkboxBottomCenterOffset.y + checkboxToTailTipDistance<br>    )<br>}</pre><p>먼저 툴팁을 배치할 때 사용할 offset을 상태로 만들었습니다.(guideTooltipOffset)</p><p>그리고 onFirstItemCheckboxPositioned 라는 첫 번째 아이템 체크박스의 onGloballyPositioned 에서 호출해줄 LayoutCoordinates 를 받는 람다를 하나 생성해주었습니다.</p><p>그리고 그 안에서는 각각의 툴팁 디자인에 맞게 LayoutCoordinates에서 참조한 좌표를 사용해서 실제로 툴팁을 배치할 offset을 계산하여 guideTooltipOffset에 할당합니다.</p><p>저는 아래 이미지처럼 부모 컴포저블 내의 위치를 일단 알고싶어서 LayoutCoordinates.boundsInParent() 함수를 사용했는데요.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tV0R9oFY82otAHVPF8WAiw.png" /><figcaption>LayoutCoordinates.boundsInParent()</figcaption></figure><p>LayoutCoordinates.boundsInParent() 외에도</p><ul><li>LayoutCoordinates.boundsInRoot()</li><li>LayoutCoordinates.boundsInWindow()</li></ul><p>의 함수도 있으니 참고하시길 바랍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nrsuw02RgaDxTazny6oiaA.png" /></figure><p>그리고 bounds…() 함수 이름에 맞게 이 함수는 Rect를 반환하는데요.</p><p>그렇기 때문에 제가 사용한 bottomCenter나 topLeft, topRight 같은 다양한 위치의 offset을 참조할 수 있습니다.🙌</p><p>이어서 진행해보면,</p><p>만든 onFirstItemCheckboxPositioned 람다를 첫 번째 아이템 Checkbox의 onGloballyPositioned에서 호출할 수 있도록 전달해줘야겠죠.</p><pre>// 리스트 컴포저블<br>@Composable<br>private fun List(<br>    products: ImmutableList&lt;Item&gt;,<br>    onItemSelected: (Item, Boolean) -&gt; Unit,<br>    isGuideTooltipVisible: Boolean,<br>    modifier: Modifier = Modifier,<br>) {<br>    Box(<br>        modifier = modifier<br>    ) {<br>        LazyVerticalGrid(columns = GridCells.Fixed(2)) {<br>            itemsIndexed(products) { index, item -&gt;<br>                StorageProductItem(<br>                    storageProductItem = item,<br>                    onItemSelected = onItemSelected,<br>                    onCheckboxPositioned = if (index == 0) {<br>                        onFirstItemCheckboxPositioned<br>                    } else {<br>                        null<br>                    }<br>                )<br>            }<br>        }<br>    }<br><br>    if (isGuideTooltipVisible) {<br>        GuideTooltip(<br>            modifier = Modifier<br>                .padding( // offset 으로 위치 설정 시 exit 애니메이션 중 컴포저블이 잘리는 이슈가 있음<br>                    start = guideTooltipOffset.x.pxToDp(),<br>                    top = guideTooltipOffset.y.pxToDp()<br>                )<br>        )<br>    }<br>}<br><br>// 리스트 아이템 컴포저블<br>@Composable<br>private fun ListItem(<br>    item: Item,<br>    onItemSelected: (Item, Boolean) -&gt; Unit,<br>    modifier: Modifier = Modifier,<br>    onCheckboxPositioned: ((LayoutCoordinates) -&gt; Unit)? = null,<br>) {<br>    Column(<br>        modifier = modifier<br>    ) {<br>        Box(<br>            modifier = Modifier<br>                .size(480.pxToDp())<br>                .clip(RoundedCornerShape(35.pxToDp()))<br>        ) {<br>            ... // 생략<br><br>            RounzMirrorCircleCheckbox(<br>                isChecked = storageProductItem.isSelected,<br>                onChecked = {<br>                    onItemSelected(storageProductItem, it)<br>                },<br>                modifier = Modifier<br>                    .padding(start = 24.pxToDp(), top = 24.pxToDp())<br>                    .size(62.pxToDp())<br>                    .then(<br>                        if (onCheckboxPositioned != null) {<br>                            Modifier.onGloballyPositioned { onCheckboxPositioned(it) }<br>                        } else {<br>                            Modifier<br>                        }<br>                    )<br>            )<br>        }<br><br>        ... // 생략<br>}</pre><p>이런식으로 onFirstItemCheckboxPositioned를 첫 번째 아이템의 체크박스까지 넘겨주었습니다.</p><p>여기까지 구현하면,</p><ol><li>첫 번째 아이템의 Checkbox의 좌표가 정해졌을 때 onFirstItemCheckboxPositioned 람다 호출됨</li><li>onFirstItemCheckboxPositioned 안에서 툴팁을 배치할 좌표를 계산하여 guideTooltipOffset 에 할당</li><li>GuideTooltip은 padding에 guideTooltipOffset 값을 사용하여 화면에 배치됨</li></ol><p>의 순서로 툴팁이 원하는 위치에 노출됩니다.😎</p><p>onGloballyPositioned를 잘 활용하면 화면 내 특정 위치에 툴팁이나 팝업을 노출해야할 때 유용할 것 같습니다.</p><p>감사합니다!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43f408d57c1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Compose] Text 한 줄일 때 LineHeight 적용하는 방법 — 디자인과 Text 높이 맞추는 방법]]></title>
            <link>https://medium.com/@seoon53/compose-text-%ED%95%9C-%EC%A4%84%EC%9D%BC-%EB%95%8C-lineheight-%EC%A0%81%EC%9A%A9%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95-%EB%94%94%EC%9E%90%EC%9D%B8%EA%B3%BC-text-%EB%86%92%EC%9D%B4-%EB%A7%9E%EC%B6%94%EB%8A%94-%EB%B0%A9%EB%B2%95-365ee5967288?source=rss-6d057e5de27c------2</link>
            <guid isPermaLink="false">https://medium.com/p/365ee5967288</guid>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[jetpack-compose-tutorial]]></category>
            <category><![CDATA[figma]]></category>
            <dc:creator><![CDATA[Minseon Cho]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 04:31:47 GMT</pubDate>
            <atom:updated>2024-11-02T05:00:47.931Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Compose] 디자인과 Text 높이 맞추는 방법 😉— LineHeightStyle</h3><p>Compose에서 TextStyle로 앱에 사용되는 텍스트 스타일을 미리 정의해놓고 쓰는 경우가 많은데요.</p><p>TextStyle에 LineHeight 를 적용하더라도 디자인과 미묘하게 다른 경험을 한번 씩 해보셨을 겁니다.</p><p>이건 안드로이드에서 LineHeight의 정의가<strong> 텍스트 baseline 사이의 거리</strong> 이기 때문입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*3rFvGRreULk8LkLppOD-6g.png" /><figcaption>1. 흔히 생각할 수 있는 LineHeight의 정의</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*JOcl21RcX9OWGCPLo4EELQ.png" /><figcaption>2. 안드로이드에서 LineHeight의 정의 (baseline간의 거리)</figcaption></figure><p>그렇기 때문에,</p><p>텍스트가 한줄일 땐 위아래에 baseline이 없으니 LineHeight가 적용되지 않는 것입니다.</p><p>여러줄인 경우에도 맨 윗줄과 맨 아랫줄은 각 위아래에 baseline이 없으니 마찬가지로 LineHeight가 적용되지 않습니다.</p><p>그런데 Figma에서 텍스트를 표시할 땐 1번처럼 LineHeight가 적용됩니다. 여기서 디자인과 개발 결과가 다른 현상이 발생하는 거죠.</p><p>이건 Text의 TextStyle을 통해서 수정할 수 있습니다.</p><p>TextStyle 코드를 보면 LineHeightStyle 항목을 볼 수 있는데요.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frQS6nHw6jQQW28lpO-n7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19kyY4LZcZT6p3Uisy6i6w.png" /></figure><p>TextStyle의 lineHeightStyle에 null을 넘겨주면 LineHeightStyle의 Default가 사용되는데,</p><p>여기서 trim의 값이 Trim.Both로 설정된 걸 보실 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlNCDin9c0L6ZMXK_5nkiA.png" /></figure><p>Trim 클래스에는 4가지 상수가 있는데 이중 Both의 설명을 읽어보면,</p><p>“첫 번째 줄의 위쪽과 마지막 줄의 아래쪽에 줄 높이로 인해 추가되는 여백을 잘라냅니다.”</p><p>라는 문장이 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*Tbim8I-68peMBSNWGtLWXA.png" /><figcaption>텍스트 한줄 일 때</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*zVQexSbosolhSbWfXoa8Qw.png" /><figcaption>텍스트 여러줄 일 때</figcaption></figure><p>즉, 위 이미지의 노란색 영역이 Trim.Both 설정으로 제거되는 것이 기본 설정인 것입니다.</p><p>이 설정때문에 Figma의 텍스트 높이와 개발 결과의 텍스트 높이가 다르게 됩니다.</p><p>이걸 Trim.None 으로 위아래 space를 제거하지 않도록 함으로써 텍스트의lineHeight 높이를 유지할 수 있습니다.</p><p>여기까지 설정했을 때</p><p>텍스트의 높이는 맞지만 실제로 텍스트가 그려지는 영역이 높이의 중간이 아닐 수 있는데요.</p><p>이건 LineHeightStyle의 나머지 항목인 Alignment 설정을 통해 해결할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W350jLV-pL9V8BLFRvkStA.png" /></figure><p>기본값은 Alignment.Proportional 입니다.</p><p>이 값은 사용하는 Font metrics를 따라가기때문에 텍스트가 중간에 위치하지 않을 수 있는데요.</p><p>Alignment.Center로 설정함으로써 텍스트를 높이 중간에 위치시킬 수 있습니다.</p><pre>val lineHeightStyle = LineHeightStyle(<br>    alignment = LineHeightStyle.Alignment.Center,<br>    trim = LineHeightStyle.Trim.None<br>)</pre><p>결과적으로,</p><p>위 코드와 같이 lineHeightStyle을 설정함으로써 Figma의 텍스트 디자인과 개발 결과가 동일하도록 만들 수 있습니다.🥳</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=365ee5967288" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Coroutines] Channel 이란?]]></title>
            <link>https://medium.com/@seoon53/coroutines-channel-%EC%9D%B4%EB%9E%80-11b2ab422f60?source=rss-6d057e5de27c------2</link>
            <guid isPermaLink="false">https://medium.com/p/11b2ab422f60</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[channel]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Minseon Cho]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 11:53:00 GMT</pubDate>
            <atom:updated>2024-10-27T11:57:51.541Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Coroutine] Channel 이란?</h3><p>Coroutine엔 Channel 이라는 개념이 있습니다. 채널은 무엇일까요?</p><h3>Channel?</h3><p>채널은 코루틴끼리 통신할 때 사용하는 기본적이고 유용한 방법으로써 공유 상태로 인한 충돌 문제가 발생하지 않습니다. 채널은 송신자/수신자의 수에 제한이 없지만 각각 하나의 코루틴을 가진 형태가 가장 일반적입니다. 또한 채널을 통해 전송된 값은 단 한번만 받을 수 있습니다.</p><p>또한,</p><p>Channel은 인터페이스이며 SendChannel, ReceiveChannel 두개의 인터페이스를 구현한 형태입니다.</p><pre>// 원소를 보내거나 채널을 닫는 용도로 사용됨<br>public interface SendChannel&lt;in E&gt; {<br>  public suspend fun send(element: E) // 중단함수이다.<br>  <br>   public fun trySend(element: E): ChannelResult&lt;Unit&gt;<br>  <br>   public fun close(cause: Throwable? = null): Boolean<br>   ...<br>}<br><br>// 원소를 받을 때 사용됨<br>public interface ReceiveChannel&lt;out E&gt; {<br>  public suspend fun receive(): E // 중단함수이다.<br><br>    public fun tryReceive(): ChannelResult&lt;E&gt;<br>    <br>    public fun cancel(cause: CancellationException? = null)<br>    ...<br>}<br><br><br>public interface Channel&lt;E&gt; : SendChannel&lt;E&gt;, ReceiveChannel&lt;E&gt;</pre><p>send와 receive는 모두 중단 함수로,</p><ul><li>send는 채널의 용량이 다 찼을 때 공간이 확보될 때 까지 중단됩니다.</li><li>receive는 호출했을 때 채널에 원소가 없다면 원소가 들어올 때 까지 중단됩니다.</li></ul><blockquote><em>💡 만약, 중단함수를 사용할 수 없다면 </em><em>trySend와 </em><em>tryReceive를 사용할 수 있습니다. 두 메서드 모두 연산의 성공/실패에 대한 결과를 ChannelResult의 형태로 반환합니다. 하지만 이 두 함수는 용량이 제한적인 채널에서만 사용할 수 있는데, 버퍼가 없는 채널에서는 작동하지 않기 때문입니다.</em></blockquote><h3><strong>채널을 만들기 위한 Channel 함수</strong></h3><p>아래 함수를 통해서 채널을 생성할 수 있습니다.</p><pre>public fun &lt;E&gt; Channel(<br>    capacity: Int = RENDEZVOUS,<br>    onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND,<br>    onUndeliveredElement: ((E) -&gt; Unit)? = null<br>): Channel&lt;E&gt; {<br> ...<br>}</pre><h4>간단한 채널 예시</h4><pre>suspend fun main(): Unit = coroutineScope {<br>    val channel = Channel&lt;Int&gt;()<br>    launch {<br>        repeat(5) { index -&gt;<br>            delay(1000)<br>            println(&quot;Producing next one&quot;)<br>            channel.send(index * 2)<br>        }<br>    }<br><br>    launch {<br>        repeat(5) {<br>            val received = channel.receive()<br>            println(received)<br>        }<br>    }<br>}<br><br><br>// (1초 후)<br>// Producing next one<br>// 0<br>// (1초 후)<br>// Producing next one<br>// 2<br>// (1초 후)<br>// Producing next one<br>// 4<br>// (1초 후)<br>// Producing next one<br>// 6<br>// (1초 후)<br>// Producing next one<br>// 8<br></pre><p>위 코드는 수신자가 얼마나 많은 데이터를 받을지에 대해 알고있어야 한다는 단점이 있습니다. 일반적으로는 이런 정보를 알지 못하기때문에 채널이 닫힐 때 까지 데이터를 받는 방식이 선호됩니다. 이를 위한 방법에는 for 루프와 consumeEach 함수를 사용할 수 있습니다.</p><h4>for loop, consumeEach 함수 예시 코드</h4><pre>suspend fun main(): Unit = coroutineScope {<br>    val channel = Channel&lt;Int&gt;()<br>    launch {<br>        repeat(5) { index -&gt;<br>            println(&quot;Producing next one&quot;)<br>            delay(1000)<br>            channel.send(index * 2)<br>        }<br>        channel.close() // 필수로 호출되어야 함!<br>    }<br><br>    // for loop<br>    launch {<br>        for (element in channel) {<br>            println(element)<br>        }<br>    }<br><br>    // 또는 consumeEach<br>    channel.consumeEach { element -&gt;<br>        println(element)<br>    }<br>}</pre><p>여기까지 보셨으면 궁금하실 수 있는 점들이 있습니다.</p><ol><li><strong>for 루프와 consumeEach는 채널이 닫혔다는 것을 어떻게 알 수 있을까요?</strong></li></ol><p>&gt;&gt; close 함수는 특별한 “닫기 토큰”을 채널에 보내는 것과 같다고 합니다. 반복 중 이 닫기 토큰을 받는 즉시 반복이 중단되는 형태이며, 따라서 닫기 전에 전송된 모든 요소의 수신이 보장될 수 있습니다.</p><p>(<a href="https://kotlinlang.org/docs/channels.html#closing-and-iteration-over-channels">출처</a>) consumeEach도 내부적으로 for 루프를 사용하는 함수이기때문에 동일한 맥락으로 채널을 닫혔다는 것을 알 수 있습니다.</p><p><strong>2. 채널이 닫힌 후 send나 receive를 하면 어떻게 될까요?</strong></p><p>&gt;&gt; 닫힌 채널에 send 호출 시 ClosedSendChannelException가 발생, receive 호출 시 채널이 비어있지 않다면 아이템을 수신 가능하며 채널이 비어있다면 ClosedReceiveChannelException 가 발생합니다.</p><p>사실 위 for 루프와 consumeEach 함수의 예시코드에서도 문제점이 있는데, 채널을 닫는 close 함수 호출을 깜빡할 수 있다는 것입니다. 특히, 예외가 발생하여 코루틴이 원소를 보내는 걸 중단하는 경우 다른 코루틴은 원소를 영원히 기다려야합니다.</p><p>이런 불편함을 해결하기 위해 produce 함수를 사용할 수 있습니다.</p><h3>produce 함수</h3><p>produce 함수는 코루틴 빌더로써 ReceiveChannel을 반환합니다. produce는 빌더로 시작된 코루틴이 어떻게 종료되든 상관없이 채널을 닫기 때문에(close를 반드시 호출하기 때문에) 안전하게 채널을 만들 수 있습니다.</p><pre>@ExperimentalCoroutinesApi<br>fun &lt;E&gt; CoroutineScope.produce(<br>    context: CoroutineContext = EmptyCoroutineContext, <br>    capacity: Int = 0, <br>    block: suspend ProducerScope&lt;E&gt;.() -&gt; Unit<br>): ReceiveChannel&lt;E&gt; { ... }<br><br>public interface ProducerScope&lt;in E&gt; : CoroutineScope, SendChannel&lt;E&gt; { ... }</pre><p>위에서 본 for loop, consumeEach 함수 예시 코드를 produce를 사용하도록 변환해보면 아래와 같습니다.</p><pre>suspend fun main(): Unit = coroutineScope {<br>    val channel = produce {<br>        repeat(5) { index -&gt;<br>            println(&quot;Producing next one&quot;)<br>            delay(1000)<br>            send(index * 2)<br>        }<br>    }<br><br>    for (element in channel) {<br>        println(element)<br>    }<br>}</pre><h3>채널 타입</h3><p>채널에 설정한 용량에 따라 4가지 타입으로 구분됩니다.</p><ol><li>무제한(Unlimited)</li></ol><p>제한이 없는 용량의 버퍼를 가진 Channel.UNLIMITED로 설정된 채널입니다. send는 중단될 일이 없고 버퍼가 비어있는 경우 receive는 중단될 수 있습니다.</p><p>2. 버퍼(Buffered)</p><p>특정 크기 또는 Channel.BUFFERED로 설정된 채널입니다. Channel.BUFFERED로 설정된 경우 기본크기는 64입니다.</p><p>버퍼가 가득 차면 send 함수는 중단되고 수신자가 원소를 소비하기를 기다립니다.</p><p>3. 랑데뷰(Rendezvous)</p><p>버퍼 용량이 0이거나 Channel.RENDEZVOUS가 설정된 채널로, 이 경우 송신자와 수신자가 만나야만 데이터가 전달됩니다. 즉, send가 먼저 호출되면 수신자가 receive를 호출할 때 까지 송신자가 중단되고 receive가 먼저 호출되면 send가 호출될 때 까지 수신자는 중단됩니다.</p><p>용량을 지정하지 않고 채널을 만드는 경우 Channel.RENDEZVOUS이 기본입니다.</p><p>4. 융합(Conflated)</p><p>버퍼 용량이 1인 Channel.CONFLATED 가 설정된 채널로, 새로운 원소가 이전 원소를 대체합니다.</p><p>즉, 수신자는 항상 최신값을 받게되며 send 함수는 중단되지 않습니다.</p><h3>버퍼 오버플로일 때</h3><p>버퍼가 꽉 찼을 때의 행동을 하단의 3가지 옵션 중 하나로 설정할 수 있습니다.</p><ul><li><strong>SUSPEND(기본 옵션)</strong> : send 메서드가 중단됨</li><li><strong>DROP_OLDEST</strong> : 가장 오래된 원소를 제거</li><li><strong>DROP_LATEST</strong> : 가장 최근의 원소를 제거</li></ul><blockquote><em>💡 </em><em>Channel.CONFLATED는 용량을 1로 설정하고 onBufferOverflow를 </em><em>DROP_OLDEST로 설정했다는 것을 추측할 수 있습니다.</em></blockquote><p>다만, 이 옵션은 produce 메서드에서는 설정할 수 없고 Channel 메서드를 사용해서 설정할 수 있습니다.</p><p>아래는 DROP_OLDEST 를 적용한 예시 코드입니다.</p><pre>suspend fun main(): Unit = coroutineScope {<br>    val channel = Channel&lt;Int&gt;(<br>            capacity = 2,<br>            onBufferOverflow = BufferOverflow.DROP_OLDEST<br>    )<br><br>    launch {<br>        repeat(5) { index -&gt;<br>            channel.send(index * 2)<br>            delay(100)<br>            println(&quot;Sent&quot;)<br>        }<br>        channel.close()<br>    }<br><br>    delay(1000)<br>    for (element in channel) {<br>        println(element)<br>        delay(1000)<br>    }<br>}<br><br>// Sent<br>// Sent<br>// Sent<br>// Sent<br>// Sent<br>// 6<br>// 8</pre><p>❗️ 주의 지금까지 채널의 타입과 버퍼 전략을 보았는데, 채널 생성 시 채널의 타입을 Channel 에 정의된 상수인 Channel.BUFFERED, Channel.RENDEZVOUS 등을 사용 할 때는 버퍼 전략에 따라 내가 설정한 채널 타입의 용량이 아닐 수 있습니다.</p><pre>// 예시) 예상한 채널 용량 64, 실제 용량 1<br>Channel&lt;Int&gt;(<br>     capacity = Channel.BUFFERED,<br>     onBufferOverflow = BufferOverflow.DROP_OLDEST<br>)</pre><p>이유는 아래의 Channel 함수의 원형을 참고해주세요.</p><pre>public fun &lt;E&gt; Channel(<br>    capacity: Int = RENDEZVOUS,<br>    onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND,<br>    onUndeliveredElement: ((E) -&gt; Unit)? = null<br>): Channel&lt;E&gt; =<br>    when (capacity) {<br>        RENDEZVOUS -&gt; {<br>            if (onBufferOverflow == BufferOverflow.SUSPEND)<br>                BufferedChannel(RENDEZVOUS, onUndeliveredElement) // an efficient implementation of rendezvous channel<br>            else<br>                ConflatedBufferedChannel(1, onBufferOverflow, onUndeliveredElement) // support buffer overflow with buffered channel<br>        }<br>        CONFLATED -&gt; {<br>            require(onBufferOverflow == BufferOverflow.SUSPEND) {<br>                &quot;CONFLATED capacity cannot be used with non-default onBufferOverflow&quot;<br>            }<br>            ConflatedBufferedChannel(1, BufferOverflow.DROP_OLDEST, onUndeliveredElement)<br>        }<br>        UNLIMITED -&gt; BufferedChannel(UNLIMITED, onUndeliveredElement)<br>        BUFFERED -&gt; { // uses default capacity with SUSPEND<br>            if (onBufferOverflow == BufferOverflow.SUSPEND) BufferedChannel(CHANNEL_DEFAULT_CAPACITY, onUndeliveredElement)<br>            else ConflatedBufferedChannel(1, onBufferOverflow, onUndeliveredElement)<br>        }<br>        else -&gt; {<br>            if (onBufferOverflow === BufferOverflow.SUSPEND) BufferedChannel(capacity, onUndeliveredElement)<br>            else ConflatedBufferedChannel(capacity, onBufferOverflow, onUndeliveredElement)<br>        }<br>    }</pre><h3>전달되지 않은 원소 핸들러</h3><p>Channel 함수에는 어떤 이유로 원소가 처리되지 않을 때 호출되는 onUndeliveredElement 파라미터도 존재합니다. 대부분의 경우는 채널이 닫히거나 취소된 경우이고 send, receive, receiveOrNull 또는 hasNext가 에러를 던질 떄도 불릴 수 있습니다.</p><pre>val channel = Channel&lt;Resource&gt;(capacity) { resource -&gt;<br>	resource.close() <br>}</pre><pre>// Producer code<br>val resourceToSend = openResource()<br>channel.send(resourceToSend)</pre><pre>// Consumer code<br>val resourceReceived = channel.receive()<br>try {<br>    // 수신한 자원으로 작업<br>} finally {<br>    resourceReceived.close()<br>}</pre><p>위 코드와 같이 채널에서 보낸 자원을 닫는데에 보통 사용되며 생산자, 소비자, 채널이 취소되더라도 열린 리소스 닫는 것을 보장할 수 있습니다.</p><h3>팬아웃, 팬인(Fan-out, Fan-in)</h3><p>코루틴에서는 여러개의 코루틴이 한 채널에서 원소를 받을 수도 있고 여러개의 코루틴이 하나의 채널로 원소를 전송할 수도 있습니다. 전자를 Fan-out, 후자를 Fan-in 이라고 부릅니다.</p><h4>팬아웃</h4><p>원소를 적절하게 처리하려면 반드시 for 루프를 사용해야합니다. consumeEach는 여러개의 코루틴이 사용하기에 안전하지 않습니다. 또한 채널은 원소를 기다리는 코루틴들을 FIFO 큐로 가지고있으므로 코루틴들은 순차적으로 원소를 받을 수 있습니다.</p><p><strong>🤔 consumeEach가 안전하지 않은 이유</strong></p><p>consumeEach는 데이터를 소비하는 processor 코루틴들이 완료되거나 실패할 때 채널을 cancel 하는 특성을 가지고 있습니다. (아래 코드 참고)</p><pre>public suspend inline fun &lt;E&gt; ReceiveChannel&lt;E&gt;.consumeEach(action: (E) -&gt; Unit): Unit =<br>    consume {<br>        for (e in this) action(e)<br>    }<br><br>public inline fun &lt;E, R&gt; ReceiveChannel&lt;E&gt;.consume(block: ReceiveChannel&lt;E&gt;.() -&gt; R): R {<br>    contract {<br>        callsInPlace(block, InvocationKind.EXACTLY_ONCE)<br>    }<br>    var cause: Throwable? = null<br>    try {<br>        return block()<br>    } catch (e: Throwable) {<br>        cause = e<br>        throw e<br>    } finally {<br>        cancelConsumed(cause) // channel을 cancel 시킨다.<br>    }<br>}</pre><p>따라서, processor 코루틴 중 하나에 오류가 발생한 상황에서 for 루프는 오류가 발생하지 않은 나머지 코루틴들이 정상적으로 값을 수신하는 반면, consumeEach는 채널의 cancel 메서드가 불리면서 채널안의 원소가 지워지고 채널이 닫히게 되어 오류가 발생하지 않은 나머지 코루틴들은 값을 수신하지 못하게 됩니다.</p><p>아래는 팬아웃 예시 코드입니다.</p><pre>fun CoroutineScope.produceNumbers() = produce {<br> repeat(10) {<br>  delay(100)<br>  send(it)<br> }<br>}<br><br>fun CoroutineScope.launchProcessor(<br> id: Int,<br> channel: ReceiveChannel&lt;Int&gt;<br>) = launch {<br> for(msg in channel) {<br>  println(&quot;#$id received $msg&quot;)<br> }<br>}<br><br>suspend fun main(): Unit = coroutineScope {<br> val channel = produceNumbers()<br> repeat(3) { id -&gt;<br>  delay(10)<br>  launchProcessor(id, channel)<br> }<br>}<br><br>// #0 received 0<br>// #1 received 1<br>// #2 received 2<br>// #0 received 3<br>// #1 received 4<br>// #2 received 5<br>// #0 received 6</pre><h4>팬인</h4><pre>suspend fun sendString(<br>    channel: SendChannel&lt;String&gt;,<br>    text: String,<br>    time: Long<br>) {<br>    while (true) {<br>        delay(time)<br>        channel.send(text)<br>    }<br>}<br><br>fun main() = runBlocking {<br>    val channel = Channel&lt;String&gt;()<br>    launch { sendString(channel, &quot;foo&quot;, 200L) }<br>    launch { sendString(channel, &quot;BAR!&quot;, 500L) }<br>    repeat(50) {<br>        println(channel.receive())<br>    }<br>    coroutineContext.cancelChildren()<br>}<br><br>// (200 ms)<br>// foo<br>// (200 ms)<br>// foo<br>// (100 ms)<br>// BAR!<br>// (100 ms)<br>// foo<br>// (200 ms)<br>// ...</pre><p>다수의 채널을 하나의 채널로 합쳐야 할 경우 아래의 코드를 참고하여 produce 함수로 여러개의 채널을 합치는 fanIn 함수를 생성해 사용할 수도 있습니다.</p><pre>fun &lt;T&gt; CoroutineScope.fanIn(<br> channels: List&lt;ReceiveChannel&lt;T&gt;&gt;<br>): ReceiveChannel&lt;T&gt; = produce {<br> for(channel in channels) {<br>  launch {<br>   for(elem in channel) {<br>    send(elem)<br>   }<br>  }<br> }<br>}</pre><h3>파이프라인</h3><p>한 채널로부터 받은 원소를 다른 채널로 전송하는 경우를 파이프라인이라고 부릅니다.</p><pre>// 1부터 3까지의 수를 가진 채널<br>fun CoroutineScope.numbers(): ReceiveChannel&lt;Int&gt; =<br>    produce {<br>        repeat(3) { num -&gt;<br>            send(num + 1)<br>        }<br>    }</pre><pre>fun CoroutineScope.square(numbers: ReceiveChannel&lt;Int&gt;) =<br>    produce {<br>        for (num in numbers) {<br>            send(num * num)<br>        }<br>    }</pre><pre>suspend fun main() = coroutineScope {<br>    val numbers = numbers()<br>    val squared = square(numbers)<br>    for (num in squared) {<br>        println(num)<br>    }<br>}<br>// 1<br>// 4<br>// 9</pre><p>여기까지, 코루틴 채널에 대해 정리한 내용이었습니다.</p><p><em>** 이 글은 Kotlin Coroutines : Deep Dive 책 내용을 참고하여 작성하였습니다.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11b2ab422f60" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>