<?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 Jeremy on Medium]]></title>
        <description><![CDATA[Stories by Jeremy on Medium]]></description>
        <link>https://medium.com/@wodbs135?source=rss-c4377c7a9b52------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qAMDo4vMCHroCiFFK8dB2g@2x.jpeg</url>
            <title>Stories by Jeremy on Medium</title>
            <link>https://medium.com/@wodbs135?source=rss-c4377c7a9b52------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:25:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wodbs135/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[Lottie Memory Optimization]]></title>
            <link>https://medium.com/@wodbs135/lottie-memory-optimization-089f9c75cdec?source=rss-c4377c7a9b52------2</link>
            <guid isPermaLink="false">https://medium.com/p/089f9c75cdec</guid>
            <category><![CDATA[lottie]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jeremy]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 10:58:38 GMT</pubDate>
            <atom:updated>2025-09-15T08:02:27.509Z</atom:updated>
            <content:encoded><![CDATA[<p>Perhaps speed improvements too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EnDjg_C-PC0qje1ToaA7DA.jpeg" /><figcaption><a href="https://unsplash.com/ko/%EC%82%AC%EC%A7%84/%EA%B0%88%EC%83%89%EA%B3%BC-%ED%9D%B0%EC%83%89-%ED%8C%90%EC%A7%80-%EC%83%81%EC%9E%90-X2RFOC4RVK8?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a>-<a href="https://unsplash.com/ko/@anniespratt?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Annie Spratt</a></figcaption></figure><p>안드로이드 개발자에게 Lottie라는 라이브러리는 매우 익숙하다.<br>다양한 애니메이션을 라이브러리 하나로 아주 쉽게 보여줄 수 있다.</p><p>내가 Lottie를 사용하며 겪게 된 메모리 최적화 관점의 소소한 팁을 공유 해보고자 한다.</p><p>상황에 대한 이해를 돕고자 예시 화면을 GPT를 들어 설명해보자.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ZiC4KMjXlTagscYU" /><figcaption>ChatGPT Voice Mode R<a href="https://i.insider.com/66f40d05ce3009a0fac94973?width=700">eference</a></figcaption></figure><p>GPT의 Voice Mode (음성 서비스)에는 이런 화면이 있다.</p><p>사용자가 말을 하면 원이 커지기도 하고 작아지기도 하며 말의 세기에 따라 반응한다.</p><p>또한, 1)음성 인식 중.. 2)생각 중.. 3)응답 중인 상태에 따라 원 내부의 인터렉션이 빠르게 변화한다.</p><p>만약 이 과정이 모두 Lottie를 통해 다양한 상태 변화에 따라 빠르게 UI를 변경시켜 보여줘야 한다면 Lottie를 계속 변경시키면 가능할 거라는 생각이 든다.</p><p>그렇게 하면 문제 없다.</p><p>다만 빠르게 상태 변화에 따라 사용자에게 보여주려면 Lottie 간 변화 시에 이질감이 없어야 한다.</p><p>로딩 시간 지연이 없는 방식을 하고자 하니 rememberLottieComposition을 사용하여 메모리에 모두 올려두니 아주 빠르게 전환이 이루어진다.</p><pre>// 상태에 따라 각각의 LottieComposition을 미리 로드해둔다.<br>val requestLottie by rememberLottieComposition(<br>            LottieCompositionSpec.Asset(Request.json)<br>)<br><br>val thinkingLottie by rememberLottieComposition(<br>            LottieCompositionSpec.Asset(Thinking.json)<br>)<br><br>val responseLottie by rememberLottieComposition(<br>            LottieCompositionSpec.Asset(Response.json)<br>)</pre><p>UX적으로 만족스럽다.</p><p>그리고 우린 상당히 많은 메모리 점유량을 얻었다.</p><p>메모리 개선을 어디서부터 할 수 있을지 찾아보자.</p><h4>Lottie의 캐시 구조</h4><p>Lottie는 LottieCompositionFactory라는 클래스의 내부에서 사용하여 LottieCompositionCache를 인스턴스로 생성하여 캐시 관리를 하고 있다.</p><p>메모리 최적화를 위해선 캐시 관리가 어떻게 이뤄지는지 필수적으로 확인이 필요하다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4SggAzmWP3czOf2eDIxYEw.png" /><figcaption>LottieCompositionCache.java</figcaption></figure><p>LottieCompositionCache를 보면 내부적으로 LRU Cache를 사용하고 있으며 maxCache 값은 20을 갖고 있다.</p><p>LottieComposition이 들어갈 수 있는 최대 갯수가 <strong>20개</strong>이다.</p><p><strong>간과하지 말아야 할 것은 LottieComposition의 갯수를 제한 두고 있을 뿐 Memory Size 자체를 제한을 두고 있지는 않다.</strong></p><p>이에 대해 Lottie-Android <a href="https://github.com/airbnb/lottie-android/issues/2260">Issue</a>에 문제가 제기된 부분이 있다.</p><p>개발자는 <strong>사용자가 스스로 Cache를 적절한 타이밍에 clear하며 관리할 수 있게 열어두고 있다</strong>고 한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mkZ9VfOuuWCACJuVm1iQxQ.png" /><figcaption><a href="https://github.com/airbnb/lottie-android/issues/2260">https://github.com/airbnb/lottie-android/issues/2260</a></figcaption></figure><p>그렇다면 그냥 캐시를 쓰지 않는 방법은 없을까?</p><pre>private fun initLottieCache() {<br>    LottieCompositionFactory.setMaxCacheSize(1) <br>}</pre><p>setMaxCache를 1로 두면 된다. (0으로 해서는 안 된다.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GgJlvghXvie9MVw45fmYjQ.png" /></figure><p>해당 코드를 통해 위에서 본 LRU Cache의 max cache 사이즈가 재지정된다.</p><p>setMaxCache를 1로 한다면 clearCache를 때에 따라 호출 할 이유는 없어보인다.</p><h4>Lottie 파일의 구조</h4><p>Lottie 파일은 디자이너로부터 전달받게 된다.</p><p>근데 로띠 파일이 너무 크다면 한 번쯤 의심해보자.<br>(내가 겪은 주요 문제는 여기서 시작된다.)</p><p>만약, 디자이너가 Lottie json 파일만 전달해주었는데 1MB를 족히 넘어가는 정도라고 해보자. (때에 따라 더 클 수도 있다..)</p><p>혹시 해당 파일 내부에 아래와 같은 부분이 있지는 않은지 확인해보자.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*3dJ2u7e-woYB-x6t1uTrLQ.png" /><figcaption>data:image/png;base64 부분</figcaption></figure><pre>{<br>  &quot;v&quot;: &quot;5.7.4&quot;,<br>  &quot;assets&quot;: [<br>    {<br>      &quot;id&quot;: &quot;image_0&quot;,<br>      &quot;w&quot;: 200,<br>      &quot;h&quot;: 200,<br>      &quot;u&quot;: &quot;&quot;,<br>      &quot;p&quot;: &quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...&quot; // 이 부분<br>    }<br>  ],<br>  &quot;layers&quot;: [...]<br>}ㅏㅐ</pre><p>이는 json 파일 내에 PNG 파일이 base64로 인코딩 되어 포함되어있다는 이야기이다.</p><p>일반적으로 Lottie를 전달해주면 Lottie를 그리는 데 필요한 이미지 리소스(PNG)를 같이 전달 줄 것이다. (경로에 맞춰서)<br>근데, 위 경우는 json 자체에 PNG가 포함 된 케이스이다.</p><p>위처럼 json에 이미지가 포함 된다면 캐싱, 재사용이 어렵다. (외부 PNG 였다면 캐시 가능하다. 이건 밑에서 자세히 이야기 해보자.)</p><p>문제가 될 수 있다.</p><h4>이게 왜 문제인가?</h4><p>Lottie-Compose에서는 Lottie Composition을 얻기 위해서는 아래와 과정을 거쳐야 한다.</p><pre>val composition = rememberLottieComposition(<br>      spec = LottieCompositionSpec.Asset(assetPath),<br>      imageAssetsFolder = imageFolder<br>)<br><br>val lottieComposition by produceState&lt;LottieComposition?&gt;(null, composition) {<br>      withContext(Dispatchers.IO) {<br>        value = composition.awaitOrNull()<br>      }<br>}<br><br>// 여기서 lottieComposition은 LottieComposition?이다.</pre><ol><li><strong>rememberLottieComposition을 통해 LottieCompositionResult를 얻는다.</strong></li></ol><ul><li>여기서 LottieCompositionResult는 State&lt;LottieComposition&gt;? 래퍼를 감싼 비동기 결과 홀더 객체이다. <br>이 과정은 백그라운드에서 LottieComposition을 로드 해오는 과정이다.</li></ul><p>2. <strong>LottieCompositionResult에서 suspend 방식으로 LottieComposition?을 꺼낸다.</strong></p><ul><li>여기서는 실제 UI 렌더링에 사용 될 LottieCompositon을 구한다.</li></ul><p>나의 경우, LottieCompositionResult를 구하는 과정과 실제 LottieComposition을 구해 오는 데에 초기에는 1~2초, 이후에는 항상 200ms 정도의 간격이 생겼다.</p><p>즉, LottieComposition을 비동기를 구해오는 과정에서 지연이 생겼다는 것이다.</p><p>이유는 위에서 언급한대로<strong> json안에 포함된 base64로 인코딩 된 이미지 소스가 매우 많았으며 이를 매번 디코딩 처리하는 과정에서 위 문제가 발생</strong>하였다.</p><blockquote>가장 처음에 언급 했던 GPT Voice Mode처럼 상태(요청, 생각, 응답)에 따라 다양한 Lottie를 빠르게 보여줘야 하는 특성 상,<strong> UI를 보여주는데에 간격이 생긴다는 것은 UX적으로 매우 문제</strong>가 된다.</blockquote><p>해결은 생각보다 간단하다.</p><p>디자이너에게 PNG 파일을 JSON으로부터 분리해달라고 요청하면 된다.</p><p>그럼 Lottie json 파일의 p 부분에는 아래와 같이 base64가 아닌 실제 경로의 png 네이밍이 적힐 것이다.</p><pre>&quot;op&quot;: 16,<br>&quot;w&quot;: 1600,<br>&quot;h&quot;: 160,<br>&quot;nm&quot;: &quot;test-json&quot;,<br>&quot;ddd&quot;: 0,<br>&quot;assets&quot;: [<br>  {<br>    &quot;id&quot;: &quot;imgSeq_0&quot;,<br>    &quot;w&quot;: 1600,<br>    &quot;h&quot;: 160,<br>    &quot;t&quot;: &quot;seq&quot;,<br>    &quot;u&quot;: &quot;images/&quot;,<br>    &quot;p&quot;: &quot;seq_0_0.png&quot;,<br>    &quot;e&quot;: 0<br>  },<br>  {<br>    &quot;id&quot;: &quot;imgSeq_1&quot;,<br>    &quot;w&quot;: 1600,<br>    &quot;h&quot;: 160,<br>    &quot;t&quot;: &quot;seq&quot;,<br>    &quot;u&quot;: &quot;images/&quot;,<br>    &quot;p&quot;: &quot;seq_0_1.png&quot;,<br>    &quot;e&quot;: 0<br>  },</pre><p>근데 내가 개선해야 할 건 <strong>속도가 아닌 메모리 문제</strong>이다.<br>(속도도 빨라졌으니 의도치 않은 행복)</p><p>근데, 왜 이게 해결책이 될까?</p><h4>base64 디코딩이 갖는 의미</h4><p>Base64는 바이너리 데이터(PNG 파일)를 문자열로 표현하기 위한 인코딩 방식이라고 생각하면 된다.</p><p>그럼 결국 실제로 UI에 PNG를 보이려면 필연적으로 아래의 과정을 거쳐야한다.</p><p><strong>1. Base64는 문자열임으로 파싱을 해야 한다.</strong></p><p>분명 해당 과정에서도 메모리에 파싱을 위해 문자열 로드를 하게 될 것이다.</p><p><strong>2. Base64 → ByteArray로 디코딩</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*947J0KjwL3PRDSPRYSSKXg.png" /></figure><p>위 코드는 <strong>rememberLottieComposition.kt</strong>의 실제 코드이다.</p><p><strong>loadImagesFromAssets</strong>을 호출하면 asset이 bitmap을 들고있지 않다면 Base64를 decode해야 한다.</p><p>이 과정에서 문자열 크기만큼 ByteArray가 생성되며 PNG가 많고 클수록 시간이 더더욱 오래 걸린다. (나의 경우, PNG가 100개가 넘는 상황이였다)</p><p><strong>3. ByteArray를 bitmap으로 디코딩</strong></p><p>위에서 본 <strong>maybeDecodeBase64Image</strong>가 호출되면 내부적으로 <strong>BitmapFactory.decodeByteArray()</strong>가 호출된다.</p><p>이는 PNG 파일인 ByteArray를 Bitmap으로 변환하는 과정이다.</p><p>결국, Base64 방식으로 PNG를 읽으려면 문자열을 메모리에 먼저 올리고 <strong>Base64 → byte array 디코딩 </strong>후<strong>, </strong>다시 <strong>PNG 압축 해제(Bitmap Decode)</strong>과정이 수반되어야 한다.</p><p>그럼, 위에서 말한 과정을 메모리 관점에서 다시 보자.</p><p>메모리 관점에서는 Base64.decode()는 Java Heap을 쓰지만, BitmapFactory가 만든 <strong>Bitmap의 픽셀 데이터</strong>는 Native Heap에 올라간다.</p><ol><li><strong>Base64를 ByteArray로 디코딩</strong><br>해당 시점에 <strong>Base64 문자열 + ByteArray PNG 데이터</strong>가 동시에 존재하기에 <strong>Java Heap 메모리가 늘어날 것이다.</strong></li><li><strong>ByteArray를 Bitmap으로 디코딩</strong><br>BitmapFactory.decodeByteArray() 호출 시, 픽셀 버퍼는 <strong>Native Heap</strong>에 생성된다.<br>Native Heap에 버퍼를 만들고 채운 뒤, Java에서 접근 가능한 <strong>Bitmap 객체</strong>를 반환한다.<br><strong>Native Heap 메모리가 늘어날 것이다.</strong></li></ol><blockquote>Bitmap이 Native Heap에 저장되는 지는 <a href="https://developer.android.com/topic/performance/graphics/manage-memory?hl=ko">Android의 비트맵 메모리 관리 방식</a>에 Android 버전 별 Bitmap의 Dalvik Heap, Native Heap 저장 여부가 다르다고 확인할 수 있다.</blockquote><p>GC가 원하는 시점에 동작 하리라는 보장이 없기에 GC가 동작하지 않는다면 계속해서 메모리는 증가할 것이다.</p><p>위에서 언급한 대로 100개가 넘는 고해상도의 PNG라면 Native Heap은 충분히 증가했을 것이다.</p><h4>그럼 실제로 줄었을까?</h4><p>Android Studio Memory Profiler를 통해 확인해보자.</p><p>아래 사진은 부팅 후, 일정 시점 뒤 확인 한 메모리 점유량이다. (AS-IS)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*_HvYK5C835wgx77Q4wt61Q.png" /></figure><p>Native Heap 영역에 해당하는 Native가 326MB를 차지하며<br>Java Heap 영역에 해당하는 Java가 66MB를 차지한다.</p><p>아래 사진은 개선 사항이 반영된 결과이다. (동일한 실험 상황)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*x5g8MwZhHiieSCQrbaeGVQ.png" /></figure><p>Native Heap 영역에 해당하는 Native가 104MB를 차지하며<br>Java Heap 영역에 해당하는 Java가 55MB를 차지한다.</p><p>PNG 분리를 통해 Native Heap 영역의 점유량을 눈에 띄게 줄일 수 있었다.</p><blockquote>다양한 실험 환경을 통해 메모리 점유량이 평균적으로 150~200MB 가량 줄었음을 확인했다.</blockquote><h4>Trade-off</h4><p>Runtime에 디코딩을 해야 하는 메모리 부담을 줄이기 위해 json 내의 base64를 PNG 파일로 분리한다면 당연히 앱이 PNG를 리소스 파일로써 들고 있어야 한다.</p><p>즉, 런타임 메모리의 부담을 줄이고 반대로 앱의 사이즈가 늘어날 수 있다.</p><h4>Lottie Memory Optimization Tip</h4><ol><li>Lottie의 캐시를 잘 사용하자.</li><li>Lottie 파일의 구조를 확인하자.</li><li>Lottie의 json이 너무 크다면 분리해보자.</li></ol><p>Lottie가 어떻게 base64를 로드 하는지, PNG를 로드 하는지 내부 과정을 거쳐 얼마나 메모리 및 속도 개선을 이뤄 낼 수 있는지 방법을 공유한다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=089f9c75cdec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cooperative Cancellation of Coroutine]]></title>
            <link>https://medium.com/@wodbs135/cooperative-cancellation-of-coroutine-4468031a51b5?source=rss-c4377c7a9b52------2</link>
            <guid isPermaLink="false">https://medium.com/p/4468031a51b5</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Jeremy]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 09:27:31 GMT</pubDate>
            <atom:updated>2025-06-15T09:27:31.390Z</atom:updated>
            <content:encoded><![CDATA[<p>Maybe developer’s responsibility</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zICGVOfggvj1ZPYzI_QwhA.jpeg" /><figcaption><a href="https://unsplash.com/ko/%EC%82%AC%EC%A7%84/%ED%9D%B0%EC%83%89%EA%B3%BC-%EA%B2%80%EC%9D%80%EC%83%89-%EC%A1%B0%EB%AA%85-%EA%B8%B0%EA%B5%AC-Em2hPK55o8g?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a> by <a href="https://unsplash.com/ko/@pastorthomasbwilson?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Tom Wilson</a></figcaption></figure><p>코루틴의 취소는 협력적이며 이를 달성하기 위해 신경쓰면 좋을 내용을 다루고자 한다.</p><p>아래의 userClickEvent 코드를 보자.</p><pre>private var requestApiJob : Job? = null<br><br>// When user do something, execute this method<br>private fun userClickEvent() {<br>    viewModelScope.launch {<br>        requestApiJob?.cancelAndJoin()<br>        requestApiJob = launch {<br>            println(&quot;Let&#39;s go to remote work.&quot;)<br>            requestApiWork()<br>        }<br>        println(&quot;Finish something work.&quot;)<br>    }<br>}<br><br>private fun requestApiWork() {<br>    var count = 0<br>    while (count &lt; 5) {<br>        count++<br>        println(&quot;Do work count : $count&quot;)<br>        Thread.sleep(500) // something blocking work.<br>    }<br>}</pre><p>requestApiJob을 cancel -&gt; join하고 새로운 job을 requestApiJob에 할당한다.</p><p>유저가 버튼을 누르는 등의 이벤트가 있다면 그때마다 userClickEvent를 호출한다.</p><p>그럼 이전에 한번에 요청을 했다면 취소가 되었을 것이다. <br>우린 그렇게 동작 되길 바란다.</p><p>정말 그렇게 동작 했을까?</p><pre>// Log<br>User 1 click             : Let&#39;s go to remote work.<br>User 1 click             : Do work count : 1<br>User 2 click after 500ms : Let&#39;s go to remote work.<br>User 1 click             : Do work count : 2<br>User 2 click             : Do work count : 1<br>User 1 click             : Do work count : 3<br>User 2 click             : Do work count : 2<br>User 1 click             : Do work count : 4<br>User 2 click             : Do work count : 3<br>User 1 click             : Do work count : 5<br>User 1 click             : Finish something work.<br>...</pre><p>2번째 요청이 있었음에도 이전 job은 취소 되지 않고 동작하였다.</p><p>코루틴에 대해 친숙한 분들에게는 어렵지 않을 내용이다.<br>문제 해결의 key는 Thread Sleep이라는 <strong>blocking 작업</strong>에 있다.</p><p>다시 이야기 하면 코루틴의 취소는 협력적이다. <br>그리고 그 협력적으로 동작하게 하기 위해 개발자가 신경 써줘야 한다.</p><blockquote><strong>협력적인 코루틴 (Cooperative Coroutine)</strong><br>- 자발적으로 멈추고, 중단되고, 취소에 응답하는 방식<br>- 취소 신호를 확인하여 필요치 않다면 자원을 빨리 반환한다.<br>- 다른 코루틴이 실행될 수 있도록 suspension point를 만든다.</blockquote><p>우리는 개발을 하면서 많은 상황에서 이전 작업을 취소하거나 취소를 보장 받아야 하는 경우가 있다.</p><p>활성(Active)화 된 job을 취소(Cancel) 한다면 바로 Cancelled가 되지 않는다.<br>아래의 그림을 보면 Cancelling 단계로 먼저 진입하며 아직 정리되지 않은 작업으로 분류된다.</p><p>이는 코루틴 내부에서 취소를 받아들이지 않은 상황이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uIuyRCUmQpWZNHq6.png" /><figcaption><a href="https://miro.medium.com/v2/resize:fit:1400/1*fZV8KpaV-CU3WmA7Kjt8_Q.png">https://miro.medium.com/</a></figcaption></figure><p>그럼 안전하게 isCancelled()를 확인하고 요청하면 되지 않을까?</p><p>아쉽게도 job.cancel()을 요청하고 취소가 완전히 되지 않았음에도 job.isCancelled()를 확인하면 true가 반환된다.</p><p>그럼 왜 취소도 안되었는데 isCancelled를 반환할까?</p><p>공식문서에서는 isCancelled는 취소 완료 여부가 아닌 <strong>취소 요청 여부</strong>로 나와있다.</p><blockquote>In the general case, it does not imply that the job has already <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/is-completed.html">completed</a>, because it may still be finishing whatever it was doing and waiting for its <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/children.html">children</a> to complete. — <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/is-cancelled.html">Coroutine isCancelled</a></blockquote><p>구조화된 동시성을 지원하는 코루틴답게 부모와 자식 관계에서 자식 job이 모두 cancel 되어야 비로소 isCompleted가 호출되어 성공/취소가 완료 됨을 알 수 있다.</p><h4>협력적인 코루틴 구현</h4><p>그럼, 코루틴 내부에서 취소를 받아 들인다는 말이 무엇일까?</p><p>우리는 지속적으로 생각해야 한다. 코루틴의 취소는 <strong>협력적</strong>이다.</p><p>현재의 작업이 취소가 가능하다고 알려줘야 한다. (즉, 협력해야 한다.)<br>이는 suspension point가 존재해야 한다는 것과 같은 의미다.</p><p>우리가 흔히 아는 suspension point는 아래와 같다.</p><ul><li>delay</li><li>withContext</li><li>yield</li><li>…</li></ul><p>각각의 쓰임에는 차이가 있지만 이는 모두 중단 포인트를 제공한다.</p><p>단편적으로는 외부에서 cancel을 요청한다면 <strong>이를 받아들이는 지점</strong>이라고 봐도 된다.</p><p>글의 서두에서 언급한 코드를 개선해보자.</p><pre>private suspend fun requestApiWork() = withContext(Dispatchers.IO) {<br>    var count = 0<br>    while (count &lt; 5 &amp;&amp; isActive) {<br>        count++<br>        println(&quot;Do remote work count : $count&quot;)<br>        Thread.sleep(500) // something blocking work.<br>    }<br>}</pre><ul><li>withContext 내에서 현재 job의 isActive 여부를 체크해서 반복문 종료를 시킬 수도 있다.</li></ul><pre>private suspend fun requestApiWork() = withContext(Dispatchers.IO) {<br>    var count = 0<br>    while (count &lt; 5) {<br>        ensureActive()<br>        count++<br>        println(&quot;Do remote work count : $count&quot;)<br>        Thread.sleep(500) // something blocking work.<br>    }<br>}</pre><ul><li>withContext를 통해 ensureActive를 통해 즉시 현재 Coroutine Scope의 활성 상태 체크를 요청할 수도 있다.</li></ul><pre>private suspend fun requestApiWork() {<br>    var count = 0<br>    while (count &lt; 5) {<br>        yield()<br>        count++<br>        println(&quot;Do remote work count : $count&quot;)<br>        Thread.sleep(500) // something blocking work.<br>    }<br>}</pre><ul><li>yield()를 통해 명시적으로 suspension point를 제공할 수 있다.</li></ul><p>그치만 yield는 코루틴 디스패칭 작업이 동반되기에 단순히 취소 여부 체크라면 성능적인 면에서 손해를 볼 수도 있다.</p><p>그럼, 이런 상황들이 보통 언제 고려 되어야 할까.<br>(간단하게 예시들을 알아보자)</p><h4>Blocking I/O 작업</h4><ul><li>일반적으로 커널 레벨에서 스레드를 멈추기에 코루틴 취소 신호를 못 받아들인다. 취소를 못 하면 자원 낭비가 예상된다.</li></ul><ol><li><strong>네트워크 통신 작업</strong></li></ol><p>요즘 유명한 OpenAI의 GPT Open API를 보면 HTTP Streaming 방식으로 서버로부터 대용량의 데이터를 지속적으로 전달 받는다.</p><p>PlayStore와 같은 앱이라면 서버를 통해 큰 용량의 APK 파일을 Streaming 방식으로 전달 받게 될 것이다.</p><p>내부적으로 InputStream.read()를 수행하는데 이는 Java Blocking I/O 작업이다. 조심스럽게 다뤄줘야 한다.</p><p><strong>2. ContentProvider, MediaStore 와 같은 System API 작업</strong></p><pre>val cursor = contentResolver.query(uri, null, null, null, null)</pre><p>위와 같이 외부 앱과 ContentProvider를 사용하여 데이터를 공유하고자 하는 작업을 할 때, Blocking 상태에 남겨질 수 있다. 특히, 앱은 생명주기에 따라 적절하게 취소를 시켜줘야 한다.</p><p><strong>3. Bluetooth를 활용하는 경우</strong></p><p>여기서도 1번과 마찬가지로 socket.inputStream.read(buffer)를 하게 되는데 이 과정에서도 InputStream.read()를 사용하여 Blocking 되게 된다.<br>상대 장치에서 데이터를 보낼 때까지 기다리게 된다.</p><p>자원이 점유되어 멈춰있게 될 것이다.</p><h4>그 외</h4><p><strong>지속적으로 API Polling 작업이 요구되는 경우</strong></p><p>특정 서비스에서 소셜 로그인을 통해 소셜 앱으로 이동 후, 다시 나의 앱으로 이동 할 때 나의 서비스에서 로그인 상태를 클라이언트에서 알아야 하는 순간이 있다면 API Polling을 하는 경우가 있을 것이다.</p><p>몇 초마다 수행하는데 그 과정에서 사용자가 화면을 이탈한다면 어떻게 처리할 것인가?<br>우린 고민해보아야 할 것이다.</p><p>앱 개발자로서 Lifecycle Awareness를 중시한다면 사소한 예외처리를 통해 자원 낭비가 없게끔 만들 수 있다.</p><h4>Flow의 취소 보장</h4><p>문득, Coroutine Flow 역시 Cancellable 하게 디자인 되어 있는데 이는 어떻게 취소/순서가 보장되는지 궁금했다.</p><p><a href="https://github.com/android/nowinandroid/blob/main/feature/search/src/main/kotlin/com/google/samples/apps/nowinandroid/feature/search/SearchViewModel.kt#L57C14-L57C27">NowInAndroid</a>에서 검색 API 호출에 사용되는 FlatMapLatest를 통해 알아보고자 한다.</p><p>우선, flatMapLatest의 경우 내부적으로 ChannelFlowTransformLatest 구현체로 연결된다.</p><pre>internal class ChannelFlowTransformLatest&lt;T, R&gt;(<br>    private val transform: suspend FlowCollector&lt;R&gt;.(value: T) -&gt; Unit,<br>    flow: Flow&lt;T&gt;,<br>    context: CoroutineContext = EmptyCoroutineContext,<br>    capacity: Int = Channel.BUFFERED,<br>    onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND<br>) : ChannelFlowOperator&lt;T, R&gt;(flow, context, capacity, onBufferOverflow) {<br>    override fun create(context: CoroutineContext, capacity: Int, onBufferOverflow: BufferOverflow): ChannelFlow&lt;R&gt; =<br>        ChannelFlowTransformLatest(transform, flow, context, capacity, onBufferOverflow)<br><br>    override suspend fun flowCollect(collector: FlowCollector&lt;R&gt;) {<br>        assert { collector is SendingCollector } // So cancellation behaviour is not leaking into the downstream<br>        coroutineScope {<br>            var previousFlow: Job? = null<br>            flow.collect { value -&gt;<br>                previousFlow?.apply {<br>                    cancel(ChildCancelledException())<br>                    join()<br>                }<br>                // Do not pay for dispatch here, it&#39;s never necessary<br>                previousFlow = launch(start = CoroutineStart.UNDISPATCHED) {<br>                    collector.transform(value)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>previousFlow라는 job을 null로 두고 상위 flow가 감지되면 previousFlow를 취소하고 join한다.</p><p>그리고 새로운 job을 할당한다.</p><p>이게 가능한 이유는 collector.transform(value)이 suspend function 이며 이는 곧 위에서 말한 suspension point를 제공하는 cancellation-cooperative 방식이기에 가능하다.</p><p><strong>그럼 suspend function이면 다 cancellation-cooperative인가?</strong></p><p>아니다.</p><pre>flow<br>    .flatMapLatest { value -&gt;<br>        flow {<br>          emit(collector.transform(value))<br>        }<br>    }<br>    .collect { }</pre><p>위의 flatMapLatest의 예시 코드를 보자.</p><p>새로운 value가 들어올 때 마다 기존 transform(value)를 처리하는 flow를 취소할 것이다.<br>왜냐면 flatMapLatest는 내부적으로 이전 coroutine scope를 취소하며 이는 emit이 <strong>suspension point</strong>를 포함하고 있기 때문이다.</p><p>결국, emit을 호출하면 구현체에 따라 suspendCancellableCoroutine으로 구현된 케이스 혹은 Channel로 구현된 케이스에서 취소 가능함을 표현한다.</p><p>아마 suspend가 아니었다면 새로운 value가 들어오더라도 이전 flow는 실행이 되었을 것이다.</p><p>이런식으로 구조적으로 협력적으로 취소 가능함을 드러내고 있다.</p><p>단순히 cancel()을 호출한다고 job이 취소가 되는게 아니며 취소를 보장 받기 위해선 개발자가 협력이 가능하게 코드를 작성해야한다.</p><p>결국 Kotlin의 협력적인 취소는 어떻게 코드를 작성 하냐에 따라 매우 비협조적이 될 수 있다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4468031a51b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Knowing Android’s intent and using Intent]]></title>
            <link>https://proandroiddev.com/knowing-androids-intent-and-using-intent-97348bfb8a45?source=rss-c4377c7a9b52------2</link>
            <guid isPermaLink="false">https://medium.com/p/97348bfb8a45</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[intent]]></category>
            <category><![CDATA[android-internals]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jeremy]]></dc:creator>
            <pubDate>Fri, 10 May 2024 05:22:58 GMT</pubDate>
            <atom:updated>2024-05-17T04:37:35.707Z</atom:updated>
            <content:encoded><![CDATA[<p>Android IPC mechanism and how we can use it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lmb_0ATrRLxPBHzNE-o6kA.jpeg" /><figcaption><a href="https://unsplash.com/ko/%EC%82%AC%EC%A7%84/%EB%AC%BC-%EC%86%8D%EC%97%90-%EB%96%A0-%EC%9E%88%EB%8A%94-%ED%81%B0-%EB%B9%99%EC%82%B0-qjs2R1lMMcw?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a>-<a href="https://unsplash.com/ko/@simonppt?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">SIMON LEE</a></figcaption></figure><p>One of the great features of the Android system design is that every app can run components of other apps, and so every component can be an EntryPoint for every app.</p><p>We’ve probably used <strong>Intent</strong> a lot in Android to communicate between components.</p><h4>What is Intent?</h4><ul><li>It is a concept used to communicate between Android components such as Activity, and is a messaging object used to specify and deliver data and actions.</li></ul><h4>So why do we use Intent?</h4><p>To answer the above question, let’s start by understanding the Android IPC concept.<br>(The reason for IPC will be explained later in the book.)</p><blockquote>This article does not cover real-world use cases for Android IPC.</blockquote><h4>IPC (Inter-Process Communication)</h4><ul><li>This refers to how different processes communicate with each other.</li></ul><p>When talking about the difference between Thread and Process, one of the most prominent characteristics that comes to mind is whether or not they can share data with each other.</p><p><strong>Processes have their own address space and behave independently.</strong><br>Therefore, Android uses a kernel space that can be shared between processes to communicate.<br>From the kernel’s perspective, a process is just a unit of work, and the data and code of tasks running in kernel space can be shared with each other.</p><p>Binders are also used to go beyond the concept of simply passing messages to use the concept of Remote Procedure Calls (RPCs), which are calls to functions in other processes.</p><p>While using an Android phone, when you use the camera, the process that drives the camera is responsible for calling the process that prints the photo to the screen.<br>So the process that runs the camera calls a function in the process that prints the photo to the screen, which is also the <strong>RPC concept</strong> mentioned above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*CZHr3j2EbLkmzUzO.png" /><figcaption><a href="https://medium.com/@esc4nor9/android-security-internals-notes-part-1-8ac593930cd2">https://medium.com/@esc4nor9/android-security-internals-notes-part-1-8ac593930cd2</a></figcaption></figure><p>To provide interprocess communication, it utilizes an abstracted driver called the Binder IPC Driver that runs in kernel space.</p><p>IPC communication is also good from a security perspective because it sends and receives data in a space that is inaccessible to users. (See figure above)</p><p>High-level IPC : <strong>Intent, Messenger, ContentProvider</strong></p><p><strong>Intent </strong>(Messaging Objects with relevant data passed to Components throughout the process),<br><strong>Messenger</strong>(Objects that enable message-based communication across processes)<br><strong>ContentProviders</strong>(Components that expose interprocess data management interfaces) <br>Android’s higher-level IPC abstractions, such as Binder, are built on top of Binder.</p><p>And service interfaces that need to be exposed to other processes can also be defined using <strong>Android Interface Definition Language (AIDL)</strong> to use the Binder as if it were a remote service call.</p><h4>Binder(with AIDL)</h4><ul><li>The Android Binder (with AIDL) is a core facility of the Android platform and is primarily used to mediate RPCs between processes.</li><li>To use the Android Binder IPC, you must have an AIDL defined.</li><li>AIDL performs IPC by decomposing objects in a way that the OS can understand and passing them between processes.</li></ul><p>At the heart of the above process is the concept of <strong>Marshaling</strong>.</p><p><strong>Marshalling</strong></p><ul><li>In Android programming, marshalling is the process of formatting data so that it can be transferred between various components.</li><li>Android is composed of various Components (Activity, Service, ContentProvider, BroadcastReceiver) and marshalling plays a very important role when these components interact with each other.</li><li><strong>In particular, marshalling is essential for interprocess communication (IPC) in Android systems.</strong></li><li><strong>Marshalling</strong><br>A procedure that converts a high-level application data structure into packets for inclusion in a binder transaction (BC_TRANSACTION).</li><li><strong>Unmarshalling</strong><br>Procedure to reconstruct a higher-level application data structure from data received via a binder transaction (BR_TRANSACTION).</li></ul><p>The term marshalling can be confusing, but marshalling refers to the <strong>process of converting a data structure or object from one representation to another for the purpose of storing or transferring data</strong>, and one type of marshalling includes <strong>serialization/deserialization.</strong></p><p>I’ve kept the description of binders short because we think it’s easier to understand the concepts I’ll discuss below if you know what they do.</p><h3>AIDL, Messenger, BroadcastReceiver, Intent</h3><h4>AIDL(Android Interface Definition Language)</h4><ul><li>In the case of BroadcastReceiver and Messenger, marshaling is required to use data passed by other processes, but with AIDL, the Android OS takes over the marshalling work based on the data types to be sent and received on a common interface, making RPC communication cleaner.</li><li>By default, the behavior is synchronous (<strong>Sync</strong>) and if you want it to run asynchronously (<strong>Async</strong>), you need to add the oneway keyword.</li></ul><h4>But how do we actually send and receive data?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*CZHr3j2EbLkmzUzO.png" /><figcaption><a href="https://medium.com/@esc4nor9/android-security-internals-notes-part-1-8ac593930cd2">https://medium.com/@esc4nor9/android-security-internals-notes-part-1-8ac593930cd2</a></figcaption></figure><ul><li>The Binder Driver manages a portion of each process’s address space.</li><li>When process A wants to send a message to process B, the Linux Kernel allocates some space in the memory of process B and copies the message data directly from process A. <br>It then queues up a short message informing process B of the incoming message. <br>It then queues up a short message to notify B of the incoming message.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*yeoSGJCCE1MpQfDR.png" /><figcaption><a href="https://jung-max.github.io/2019/08/27/Android-Kernel-System-Memory-Model/">https://jung-max.github.io/2019/08/27/Android-Kernel-System-Memory-Model/</a></figcaption></figure><ul><li>The figure above shows that while each process has its own memory area, there are some parts of it that can be shared by the kernel.(Kernel Space Virtual addresses)</li></ul><p>This is how data sharing is possible.</p><h4>Messenger</h4><pre>public final class Messenger implements Parcelable {</pre><ul><li>Messenger is a reference to a Handler that other processes can use to send messages to other processes.</li></ul><p>In other words, the <strong>Handler depends on a Thread in the current process, and it is the Messenger that makes the reference available to other processes.</strong><br>Again, the Messenger is also part of the IPC.</p><ul><li>When you create a Messenger, you specify a Handler, which eases the marshalling part and makes it easier to communicate between Processes.</li><li>It depends on a ‘<strong>Handler</strong>’ that is associated with a single thread and handles the event queue of that thread.</li></ul><p>Therefore, it is better to create and assign a separate Background (Worker) Thread rather than a Main Thread.</p><ul><li>Serves all requests from the client in a single thread and only receives one request at a time (what we call <strong>thread-safe</strong>).</li><li>It is only used for async communication.</li><li>Binder + Predefined AIDL + Restricted Thread (Handler)</li></ul><p>It is more limited than AIDL and is better suited for passing simple types than for passing Custom Objects. <br>For passing complex data structures and types, it is better to implement and use AIDL.</p><h4>BroadcastReceiver</h4><ul><li>BroadcastReceivers can be sent by the system or by applications.<br>Applications can use BroadcastReceiver to register to receive specific BroadcastReceivers.</li><li>It is used for loosely coupled communication between different components or application.</li></ul><p>When delivering a broadcast, you will perform a sendBroadcast in the current Context.</p><pre>private fun sendBroadcast(){<br>    val intent = Intent()<br>    intent.action = &quot;com.sample.jeremy.broadcast&quot;<br>    intent.putExtra(PACKAGE_NAME, context?.packageName)<br>    intent.putExtra(PID, Process.myPid().toString())<br>    intent.putExtra(DATA, &quot;data that you want to use&quot;)<br>    intent.component = ComponentName(&quot;com.sample.jeremy.lib&quot;, &quot;com.sample.jeremy.lib.BroadcastReceiver&quot;)<br>    activity?.applicationContext?.sendBroadcast(intent)<br>}</pre><p>As shown above, we utilize an Intent to define an <strong>action</strong>, <strong>component</strong>, and call <strong>sendBroadcast</strong>. <br>How is this received?</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    package=&quot;com.sample.jeremy.lib&quot;&gt;    <br>    &lt;application<br>        android:allowBackup=&quot;true&quot;<br>        android:icon=&quot;@mipmap/ic_launcher&quot;<br>        android:label=&quot;@string/app_name&quot;<br>        android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;<br>        android:supportsRtl=&quot;true&quot;&gt;<br>        &lt;activity android:name=&quot;.MainActivity&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br>                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/activity&gt;<br>        &lt;receiver android:name=&quot;.BroadcastReceiver&quot;<br>            android:enabled=&quot;true&quot;<br>            android:exported=&quot;true&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;com.sample.jeremy.broadcast&quot; /&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/receiver&gt;<br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><pre>class BroadcastReceiver: BroadcastReceiver() {<br>    override fun onReceive(context: Context?, intent: Intent?) {<br>        val data = intent?.getStringExtra(DATA)<br>        // You can pull the data out of the intent on this line and utilize it.<br>    }<br>}</pre><p>Above is the AndroidManifest for the lib that will actually be received.<br>The <strong>&lt;intent-filter&gt;</strong> is the part to watch out for. <br>The sender can set the same <strong>Tag</strong> (com.sample.jeremy.broadcast) value as the one specified in the action and filter it to receive the Intent.</p><p>If you’ve ever used an Intent to call another Activity with startActivity(), you’ll recognize the similarities.<br>Defining and throwing an <strong>Intent</strong>, filtering it with <strong>Intent-filter</strong>…</p><p>Pay attention to the part that says ComponentName. <br>And now let’s take a look at the <strong>Intent</strong>.</p><h4>Intent</h4><ul><li>It’s a universal communication medium between app components.</li></ul><p><a href="https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/java/android/content/Intent.java?q=intent.java">The official documentation code</a> also states that <br>It is utilized in <strong>startActivity to perform an activity</strong> and in <strong>broadcastIntent</strong> for <strong>broadcastIntent for a BroadcastReceiver</strong> and <br>For <strong>Background Service, Intent is utilized in both startService and bindService</strong>. <br>(Proof that it is a communication medium between components)</p><ul><li>You only need to specify the <strong>target component</strong> or the <strong>general action</strong> to be performed.</li></ul><p>As you know, this is kind of <strong>Implicit Intent</strong> and <strong>Explicit Intent.</strong></p><ul><li>Conception of Messenger + Connection Control</li></ul><p><strong>An Intent is basically composed of an Action and Data.</strong></p><p>And there are a few Action+Data pairs already defined.</p><blockquote>action: ACTION_VIEW | data : tel:123</blockquote><ul><li>The above Intent will display a phone dialer with the 123 number entered.</li></ul><p>There are pre-defined Action values, which you can also customize and use.<br>ex) ACTION_MAIN, ACTION_VIEW, ACTION_EDIT</p><pre>&lt;intent-filter&gt;<br>      &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>      &lt;action android:name=&quot;android.intent.action.EDIT&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><p>When using Explicit Intent, we typically utilize Intent to transition between Activities, as shown below.</p><pre>startActivity(<br>    Intent(<br>        this, // current context <br>        MainActivity::class.java<br>    ).apply { <br>        putExtra(&quot;stringKey&quot;,&quot;string data&quot;) // data <br>        putExtra(&quot;parcelableKey&quot;, Person(1)) // require parcelize<br>    }<br>)</pre><p>this contains the currently running Activity, followed by the targetActivity to run.</p><p>When passing data, serialization is mandatory for Custom Objects.</p><p>Let’s take the IPC concepts you read above and use them to answer some of the questions you might have about using Intents.</p><h4>Why is serialization necessary when communicating between Activity on Android?</h4><ul><li>Let’s relate the concepts from the <strong>Binder</strong> system above.<br><strong>The OS and the process in which the Activity runs are different. </strong><br>When executed in a different process, we said that we need to use IPC to pass data.<br>Remember that an Intent is a high-level abstraction of an IPC, and you’ll eventually see why we need to use Intent.</li></ul><h4>So are all Activity is different processes? I thought Intent was a high-level abstraction of IPC, but isn’t IPC inter-process communication?</h4><ul><li>You need to consider the lifecycle.<br>Imagine that when passing data from MainActivity to DetailActivity, DetailActivity accesses a value that MainActivity holds statically.<br>But what happens if the MainActivity is blown out of memory by a Memory Killer?<br><strong>The DetailActivity would have no object to reference.</strong></li><li>That’s the reason why we use IPC.</li><li>By default, Activity declared in one Application have the same Process Id unless you specify a process when declaring the Activity in the Manifest.</li></ul><p>It is also along the same lines as above when storing custom objects in the bundled values of onSaveInstanceState() and onRestoreInstanceState() to prevent data from being lost in the event of activity recreation.</p><pre>override fun onSaveInstanceState(outState: Bundle) {<br>      outState.putParcelable(&quot;key&quot;, Person()) // save parcelable custom objects<br>      super.onSaveInstanceState(outState)<br>}<br><br>override fun onRestoreInstanceState(savedInstanceState: Bundle) {<br>      super.onRestoreInstanceState(savedInstanceState)<br>      val person = savedInstanceState.getParcelable&lt;Person&gt;(&quot;key&quot;) // get parcelable custom objects<br>}</pre><p>Think of a new Activity being created and passing a value to the new Activity.</p><p>If they all need to see the same value, marshalling (serialization) would be necessary, just like passing Custom Objects when communicating between Activity with Intent.</p><p><strong>Extra)</strong> If startActivity() specifies as its first parameter <strong>this</strong></p><h4>Why do we need the current packageContext when we can pass the packageContext to the startActivity call when we have an explicit intent?</h4><pre>Intent(Context packageContext, Class&lt;?&gt; cls) {<br>      mComponent = new ComponentName(packageContext, cls);<br>}<br><br>ComponentName(Context pkg, String cls) {<br>      if (cls == null) throw new NullPointerException(&quot;class name is null&quot;);<br>      mPackage = pkg.getPackageName(); // Context method <br>      mClass = cls; <br>}</pre><ul><li>Inside the Intent code, we use the <strong>packageContext</strong> and<strong> Class information</strong> as above to get the information called <strong>ComponentName</strong>.</li><li>The packageName used here is a method of Context(interface), which allows you to get the package information of the current Application.</li><li>This is why explicit intent is often used when moving from the current Application to an accessible Activity, as it requires specifying both the subject to be executed and the subject to be executed. (same package)</li></ul><p>As I studied Intent, I realized that I needed to understand the IPC concept, so I also explained Messenger, AIDL, and BroadcastReceiver.</p><p>When I was using Intent, there were a lot of things I used without really thinking about it, and I hadn’t really thought about it in relation to the Android Framework, so I thought this was a good concept post.</p><p>I should know Android’s Intent and use Intent too.</p><h4>Reference</h4><ul><li><a href="https://tech.buzzvil.com/seminar/tech-weekly-android-ipc-mechanisms-2/">Buzzvill Tech Blog</a></li><li><a href="https://medium.com/@begalesagar/why-do-we-need-to-use-serializable-parcelable-for-passing-custom-object-from-one-activity-to-eb78f51fadaa">Medium — Passing Custom Object from Activity to Activity</a></li><li><a href="https://null-android-pentesting.netlify.app/src/android-internals">Android Internals</a></li><li><a href="https://d2.naver.com/helloworld/47656">Naver d2 Android</a></li><li><a href="https://events.static.linuxfound.org/images/stories/slides/abs2013_gargentas.pdf">Deep dive into Android Binder Framework</a></li><li><a href="https://medium.com/@ledubmurukp/android-system-ipc-mechanisms-3d3b46affa3c">Medium — Android IPC Mechanism</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97348bfb8a45" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/knowing-androids-intent-and-using-intent-97348bfb8a45">Knowing Android’s intent and using Intent</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[의도(Intent)를 알고 사용하기]]></title>
            <link>https://medium.com/@wodbs135/%EC%9D%98%EB%8F%84-intent-%EB%A5%BC-%EC%95%8C%EA%B3%A0-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0-d724e9d938d7?source=rss-c4377c7a9b52------2</link>
            <guid isPermaLink="false">https://medium.com/p/d724e9d938d7</guid>
            <category><![CDATA[intent]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[broadcastrecei]]></category>
            <category><![CDATA[ipc]]></category>
            <category><![CDATA[messenger]]></category>
            <dc:creator><![CDATA[Jeremy]]></dc:creator>
            <pubDate>Thu, 09 May 2024 06:51:29 GMT</pubDate>
            <atom:updated>2024-05-09T06:51:29.901Z</atom:updated>
            <content:encoded><![CDATA[<p>Android IPC mechanism and how we can use it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lmb_0ATrRLxPBHzNE-o6kA.jpeg" /><figcaption><a href="https://unsplash.com/ko/%EC%82%AC%EC%A7%84/%EB%AC%BC-%EC%86%8D%EC%97%90-%EB%96%A0-%EC%9E%88%EB%8A%94-%ED%81%B0-%EB%B9%99%EC%82%B0-qjs2R1lMMcw?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a>-<a href="https://unsplash.com/ko/@simonppt?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">SIMON LEE</a></figcaption></figure><p>Android System 디자인의 가장 큰 특징 중 하나는 모든 앱은 서로 다른 앱의 컴포넌트를 실행시킬 수 있다는 것이며 그래서 각 컴포넌트들은 모두 각 앱의 진입점(EntryPoint)이 될 수 있다는 것이다.</p><p>우리는 Android에서 컴포넌트 간 통신 시에 Intent를 자주 사용했을 것이다.</p><h4><strong>Intent란 무엇인가?</strong></h4><ul><li>Activity와 같은 Android Component 간 소통하는데 사용 되는 개념으로 Data와 Action을 명시하여 전달할 때 사용하는 메세징 객체이다.</li></ul><p><strong>그럼 우린 왜 Intent를 사용하는가?</strong></p><p>위 물음에 대한 답을 위해 Android IPC 개념부터 이해하며 답을 찾아보자.<br>(IPC가 왜 나오는지는 읽다보면 자연스럽게 알게 될 것이다.)</p><h4>IPC (Inter-Process Communication)</h4><ul><li>서로 다른 프로세스 간 통신하는 방법을 말한다.</li></ul><p>Thread와 Process의 차이를 이야기 할 때, 가장 대표적으로 떠오르는 특징 중 하나가 <strong>데이터를 서로 간에 공유 할 수 있는 지</strong> 여부이다.</p><p>프로세스는 <strong>각자 독립적인 주소 공간을 갖고 별개로 동작</strong>한다.<br>그래서 안드로이드에서는 프로세스 간 공유가 가능한 커널 공간을 이용해서 대화를 한다.<br>커널 입장에서 봤을 때 프로세스는 하나의 작업 단위일 뿐이고, 커널 공간에서 실행하는 Task의 데이터와 코드는 서로 공유될 수 있다.</p><p>단순히 메세지를 전달하는 개념을 넘어서 다른 프로세스에 있는 함수를 호출하는 RPC(Remote Procedure Call)의 개념을 사용하기 위해 Binder를 사용하기도 한다.</p><p>안드로이드 폰을 사용할 때, 카메라를 사용한다면 카메라를 구동하는 프로세스가 사진을 화면에 출력하는 프로세스까지 같이 담당한다. <br>그래서 카메라 구동 프로세스에서 사진 출력 프로세스의 함수를 호출하는 식으로 동작하며 이는 위에서 언급한 RPC 개념 이기도 하다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*CZHr3j2EbLkmzUzO.png" /><figcaption><a href="https://medium.com/@esc4nor9/android-security-internals-notes-part-1-8ac593930cd2">https://medium.com/@esc4nor9/android-security-internals-notes-part-1-8ac593930cd2</a></figcaption></figure><p>프로세스 간 통신을 제공하기 위해 커널 공간에서 동작하는 Binder IPC Driver 라는 추상화 된 드라이버를 이용한다.<br>사용자가 접근할 수 없는 공간에서 데이터를 주고 받기에 IPC 통신은 보안적인 부분에서 좋기도 하다. (위 그림 참고)</p><p>상위 수준의 IPC 방식 : <strong>Intent, Messenger, ContentProvider</strong></p><p><strong>Intent </strong>(프로세스 전반의 Component에 전달되는 관련 데이터가 있는 명령어),<br><strong>Messenger</strong>(프로세스 전반에서 메시지 기반 통신을 가능하게 하는 객체)<br><strong>ContentProviders</strong>(프로세스 간 데이터 관리 인터페이스를 노출하는 컴포넌트) 등의 Android의 상위 수준 IPC 추상화는 Binder를 기반으로 구축된다.</p><p>그리고 다른 프로세스에 노출해야하는 서비스 인터페이스는 마치 원격 서비스 호출처럼 사용하기 위해 <strong>AIDL(Android Interface Definition Language)</strong>을 사용하여 Binder를 정의할 수도 있다.</p><h4>Binder(with AIDL)</h4><ul><li>Android Binder(with AIDL)는 Android 플랫폼의 핵심 설비로서 각 프로세스 간에 수행되는 RPC를 중재하는 역할로 주로 사용한다.</li><li>Android Binder IPC를 사용하기 위해선 AIDL이 정의되어 있어야 한다.</li><li>AIDL은 객체를 OS가 이해할 수 있는 방식으로 분해하고 이를 프로세스 간에 전달하여 IPC를 수행한다.</li></ul><p>위 과정의 핵심에는 <strong>Marshalling</strong>이라는 개념이 있다.</p><p><strong>Marshalling(마샬링)</strong></p><ul><li>안드로이드 프로그래밍에서 마샬링(marshalling)이란 다양한 구성 요소 간 데이터를 전송할 수 있도록 데이터를 포맷 하는 과정을 말한다.</li><li>안드로이드는 다양한 Component(Activity, Service, ContentProvider etc)로 이루어져 있으며, 이러한 Component들이 상호 작용할 때 마샬링은 매우 중요한 역할을 한다. <br>특히, 안드로이드 시스템에서는 프로세스 간 통신(IPC)을 할 때 마샬링이 필수적이다.</li><li><strong>Marshalling</strong><br>바인더 트랜잭션(BC_TRANSACTION)에 포함할 목적으로 상위 레벨 애플리케이션 데이터 구조를 패킷으로 변환하는 절차이다.</li><li><strong>Unmarshalling</strong><br>바인더 트랜잭션을 통해 수신된 데이터(BR_TRANSACTION)에서 상위 수준의 애플리케이션 데이터 구조를 재구성하는 절차이다.</li></ul><p>마샬링이라고 하니까 어색할 수 있는데 마샬링은<strong> 데이터를 저장하거나 전송할 목적으로 데이터 구조 또는 개체를 한 표현에서 다른 표현으로 변환하는 프로세스</strong>를 말한다고 생각하면 되며 마샬링의 한 종류에는<strong> 직렬화 / 역직렬화</strong> 역시 이에 포함되는 개념이다.</p><p>Binder가 뭘 하는지 알아야 아래의 개념들이 더 이해하기 쉬울거라 판단하여 짧게나마 Binder를 설명하였다.</p><h3><strong>AIDL, Messenger, BroadcastReceiver, Intent</strong></h3><h4>AIDL(Android Interface Definition Language)</h4><ul><li>BroadcastReceiver, Messenger의 경우, 다른 프로세스에서 전달한 data를 사용하기 위해서 마샬링을 해야 하지만 AIDL을 사용하면 공통된 인터페이스에서 주고 받을 data type을 토대로 Android OS가 마샬링 작업을 대신 수행해주어 RPC 통신이 좀 더 깔끔 해 질 수 있다.</li><li>기본적으로 동작 방식은 동기적(Sync)이며 비동기(Async)로 실행을 원하면 oneway 키워드를 붙여야 한다.</li></ul><p><strong>그럼 실제로 어떻게 데이터를 주고 받을까?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*CZHr3j2EbLkmzUzO.png" /><figcaption><a href="https://medium.com/@esc4nor9/android-security-internals-notes-part-1-8ac593930cd2">https://medium.com/@esc4nor9/android-security-internals-notes-part-1-8ac593930cd2</a></figcaption></figure><ul><li>Binder Driver는 각 프로세스의 주소 공간 일부를 관리한다.</li><li>A 프로세스가 B 프로세스에 메세지를 보내고자 한다면, Linux Kernel은 B 프로세스의 메모리에 일부 공간을 할당하고 A 프로세스에서 직접 메세지 데이터를 복사한다. <br>그리고 B 프로세스에 수신 메세지를 알려주는 짧은 메세지를 큐에 대기시킨다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*yeoSGJCCE1MpQfDR.png" /><figcaption><a href="https://jung-max.github.io/2019/08/27/Android-Kernel-System-Memory-Model/">https://jung-max.github.io/2019/08/27/Android-Kernel-System-Memory-Model/</a></figcaption></figure><ul><li>위의 그림과 같이 프로세스가 가질 고유한 메모리 영역은 존재하지만 일부는 kernel이 공유 가능한 부분이 있다는 것을 보여 준다.<br>이를 통해 데이터 공유가 가능한 것이다.</li></ul><h4><strong>Messenger</strong></h4><pre>public final class Messenger implements Parcelable {</pre><ul><li>다른 프로세스가 메시지를 보내는 데 사용할 수 있는 Handler에 대한 참조이다.<br>쉽게 말하면, <strong>Handler는 현재 프로세스 내 Thread에 바인딩 되는데 이를 다른 프로세스에서 사용 가능하도록 참조를 만드는게</strong> Messenger이다.<br>다시 말하지만, Messenger도 IPC의 하나이다.</li><li>Messenger 생성 시, Handler를 지정하게 되고 이렇게 되면 마샬링하는 부분을 편하게 해주어 Process 사이 통신이 편하다.</li><li>단일 스레드와 연결되어 해당 스레드의 이벤트 대기열을 처리하는 ‘<strong>Handler</strong>’에 따라 달라 지게 된다. 그렇기에 Main Thread 보단 Background(Worker) Thread를 별도 생성하여 할당하는게 나을 것이다.</li><li>Client의 요청을 단일 스레드에서 모두 수행하며 한번에 하나의 요청만 받는다. (<strong>Thread-Safe</strong>하다는 것)</li><li>오직 비동기(Async) 통신에서만 사용된다.</li><li>Binder + Predefined AIDL + Restricted Thread (Handler) 개념이라고 생각하면 된다.</li></ul><p>AIDL에 비해 제한적인 부분이 많고 Custom Objects를 전달하기 보단 간단한 타입의 전달이 적당하다. <br>복잡한 데이터 구조와 타입을 전달하기 위해선 AIDL을 구현해 사용하는 편이 나을 것이다.</p><h4>BroadcastReceiver</h4><ul><li>BroadcastReceiver는 시스템 또는 Application에서 전송할 수 있으며<br>Application은 BroadcastReceiver를 사용하여 특정 BroadcastReceiver를수신하도록 등록할 수 있다.</li><li>서로 다른 Component 또는 애플리케이션 간의 느슨하게 결합된 통신에 사용된다.</li></ul><p>Broadcaast를 전달할 때는 현재 Context에서 sendBroadcast를 수행하게 된다.</p><pre>private fun sendBroadcast(){<br>    val intent = Intent()<br>    intent.action = &quot;com.sample.jeremy.broadcast&quot;<br>    intent.putExtra(PACKAGE_NAME, context?.packageName)<br>    intent.putExtra(PID, Process.myPid().toString())<br>    intent.putExtra(DATA, &quot;data that you want to use&quot;)<br>    intent.component = ComponentName(&quot;com.sample.jeremy.lib&quot;, &quot;com.sample.jeremy.lib.BroadcastReceiver&quot;)<br>    activity?.applicationContext?.sendBroadcast(intent)<br>}</pre><p>위와 같이 Intent를 활용하여 action, component를 정의하고 sendBroadcast를 호출한다. <br>이는 어떻게 수신이 되는가?</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    package=&quot;com.sample.jeremy.lib&quot;&gt;    <br>    &lt;application<br>        android:allowBackup=&quot;true&quot;<br>        android:icon=&quot;@mipmap/ic_launcher&quot;<br>        android:label=&quot;@string/app_name&quot;<br>        android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;<br>        android:supportsRtl=&quot;true&quot;&gt;<br>        &lt;activity android:name=&quot;.MainActivity&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br><br>                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/activity&gt;<br>        &lt;receiver android:name=&quot;.BroadcastReceiver&quot;<br>            android:enabled=&quot;true&quot;<br>            android:exported=&quot;true&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;com.sample.jeremy.broadcast&quot; /&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/receiver&gt;<br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><pre>class BroadcastReceiver: BroadcastReceiver() {<br>    override fun onReceive(context: Context?, intent: Intent?) {<br>        val data = intent?.getStringExtra(DATA)<br>        //여기서 intent에서 데이터를 꺼내서 활용하면 된다.<br>    }<br>}</pre><p>위는 실제로 수신 받을 lib 쪽의 AndroidManifest이다. <br>주의해서 볼 부분은 <strong>&lt;intent-filter&gt;</strong>이다. 보내는 쪽에서 <strong>action</strong>에 명시한 Tag(com.sample.jeremy.broadcast) 값을 동일하게 설정하여 필터링 처리하여 Intent를 수신 받을 수 있다.</p><p>Intent를 사용하여 startActivity로 다른 Activity를 호출 해 본 경험이 한 번이라도 있다면 유사한 부분을 찾을 수 있다.<br>Intent를 정의하여 던진다는 점, Intent-filter로 필터링 하는 부분..</p><p>ComponentName이라고 명시된 부분을 주의 깊게 보자. <br>그리고 이제 Intent를 들여다보자.</p><h4><strong>Intent</strong></h4><ul><li>앱 구성 요소(Component) 간 범용적인 커뮤니케이션 매체이다.</li></ul><p><a href="https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/java/android/content/Intent.java?q=intent.java">공식 문서 코드</a>에도 명시되어 있지만 <br>Activity 수행을 위해서 startActivity에 활용되고<br>BroadcastReceiver를 위해서 broadcastIntent로 사용되고 <br>Background Service를 위해서 startService 혹은 bindService 시에 Intent가 모두 활용된다. (컴포넌트 간 커뮤니케이션 매체라는 증거)</p><ul><li>오직 타겟 컴포넌트 혹은 수행 할 일반적인 액션만 명시 하면 된다.<br>- 흔히 아는 <strong>명시적 인텐트</strong>와 <strong>암시적 인텐트</strong>라고 생각하면 된다.</li><li>Messenger + Connection Control 개념이라고 생각하면 된다.</li></ul><p><strong>Intent는 기본적으로 Action과 Data로 구성된다.</strong></p><p>그리고 이미 정의된 Action+Data 쌍이 몇가지 있다.</p><ul><li>action: ACTION_VIEW | data : tel:123 <br>위와 같은 Intent를 수행하면 123 번호가 입력된 전화 다이얼러를 표시하게 된다.</li></ul><p>이미 정의된 Action 값들이 있으며 사용자가 정의해서 사용할 수도 있다. <br>ex) ACTION_MAIN, ACTION_VIEW, ACTION_EDIT</p><pre>&lt;intent-filter&gt;<br>      &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>      &lt;action android:name=&quot;android.intent.action.EDIT&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><p>우리는 보통 명시적 인텐트를 사용 시, 아래와 같이 Activity 간 전환 시에 Intent를 활용한다.</p><pre>startActivity(<br>    Intent(<br>        this, // current context <br>        MainActivity::class.java<br>    ).apply { <br>        putExtra(&quot;stringKey&quot;,&quot;string data&quot;) // data <br>        putExtra(&quot;parcelableKey&quot;, Person(1)) // require parcelize<br>    }<br>)</pre><p>this는 현재 실행 중인 Activity가 들어가고 그 다음엔 실행 시킬 대상Activity가 들어간다.</p><p>데이터를 넘길 경우, Custom Objects의 경우 직렬화가 필수이다.</p><p>지금부터 위에서 읽은 IPC 개념을 토대로 Intent를 사용할 때 가질 수 있는 의문점들을 풀어보자.</p><h4>Android에서 Activity 간 통신 시에 직렬화가 필요한 이유가 뭘까?</h4><ul><li>위에서 본 <strong>Binder</strong> 시스템의 개념을 생각하면 된다.<br>OS와 Activity가 실행되는 Process는 다르다. <br>다른 프로세스에서 수행되면 데이터 전달 시, IPC를 해야 한다고 했다.<br>Intent는 고수준으로 추상화 시킨 IPC임을 기억하면 결국 왜 Intent를 사용하여야 하는지 알 것이다.</li></ul><h4>그럼 모든 Activity는 서로 다른 프로세스인가? Intent는 IPC의 고수준 추상화라고 했는데 IPC는 프로세스 간 통신 아닌가?</h4><ul><li>Activity는 고유한 Lifecycle을 갖고 있기에 특정 Activity에 static한 값을 공유한다면 분명히 특정 Activity가 파괴 되었을 때, 명확하게 해당 값을 가져오지 못할 가능성이 높다.</li><li>우린 <strong>Lifecycle</strong>을 고려해야 한다. <br>MainActivity에서 DetailActivity로 데이터를 전달 할 때, MainActivity에서 static하게 갖고 있는 값을 DetailActivity에서 접근하다고 해보자.<br>근데 MainActivity가 Memory Killer에 의해 메모리에서 날아가면 어떻게 될까?<br><strong>DetailActivity는 바라볼 객체가 없을 것이다.</strong></li><li>위의 문제를 해결하기 위해 IPC를 사용하는 것이다.</li><li>기본적으로 Manifest에서 Activity 선언 시에 process를 별도로 지정하지 않으면 하나의 Application에 선언된 Activity는 동일한 Process Id를 갖는다.</li></ul><p>추가로 우린 Activity 재생성에 대해서 onSaveInstanceState(), onRestoreInstanceState()에서 Bundle 값에 Custom Objects를 저장하는 경우를 생각해봐도 같은 맥락이다.</p><pre>override fun onSaveInstanceState(outState: Bundle) {<br>      outState.putParcelable(&quot;key&quot;, Person()) // save parcelable custom objects<br>      super.onSaveInstanceState(outState)<br>}<br><br>override fun onRestoreInstanceState(savedInstanceState: Bundle) {<br>      super.onRestoreInstanceState(savedInstanceState)<br>      val person = savedInstanceState.getParcelable&lt;Person&gt;(&quot;key&quot;) // get parcelable custom objects<br>}</pre><p>새로운 Activity가 생성되는 것과 새로운 Activity에 값을 전달하는 것을 생각해보면 된다. <br>모두 같은 값을 봐야 한다면 Intent로 Activity 간 통신 시, Custom Objects를 전달하는 것처럼 마샬링(직렬화) 과정이 필요할 것이다.</p><p><strong>번외)</strong> startActivty()에서 this로 명시하는 경우</p><h4>명시적 intent를 할 때, startActivity 호출 시에 packageContext를 전달해야 하는 경우에 왜 현재 packageContext가 필요할까?</h4><pre>Intent(Context packageContext, Class&lt;?&gt; cls) {<br>      mComponent = new ComponentName(packageContext, cls);<br>}<br><br>ComponentName(Context pkg, String cls) {<br>      if (cls == null) throw new NullPointerException(&quot;class name is null&quot;);<br>      mPackage = pkg.getPackageName(); // Context method <br>      mClass = cls; <br>}</pre><ul><li>Intent 코드의 내부에서는 위와 같이 packageContext와 Class 정보를 사용하여 <strong>ComponentName</strong>이라고 하는 정보를 갖고온다.</li><li>여기서 사용되는 packageName은 Context(interface)의 메소드이며 이를 통해 현재 Application의 패키지 정보를 획득할 수 있다.</li><li>명시적 intent는 실행 할 주체와 실행 될 주체를 모두 명시해야 하기에 현재 Application 에서 접근 가능한 Activity로 이동할 때, 주로 사용하는 이유이기도 하다. (같은 패키지)</li></ul><p>Intent를 공부하면서 IPC 개념에 대한 이해가 필요하다 싶었고 그래서 Messenger, AIDL, BroadcastReceiver도 같이 설명하게 되었다.</p><p>Intent를 사용할 때, 깊게 고민하지 않고 사용한 부분이 많았으며 Android Framework와 연관 지어 고민해 본 경험이 없었기에 필요한 개념 글이라고 생각했다.</p><p>나도 의도(Intent)를 알고 사용 해야겠다.</p><h4>Reference</h4><ul><li><a href="https://tech.buzzvil.com/seminar/tech-weekly-android-ipc-mechanisms-2/">Buzzvill Tech Blog</a></li><li><a href="https://medium.com/@begalesagar/why-do-we-need-to-use-serializable-parcelable-for-passing-custom-object-from-one-activity-to-eb78f51fadaa">Medium — Passing Custom Object from Activity to Activity</a></li><li><a href="https://null-android-pentesting.netlify.app/src/android-internals">Android Internals</a></li><li><a href="https://d2.naver.com/helloworld/47656">Naver d2 Android</a></li><li><a href="https://events.static.linuxfound.org/images/stories/slides/abs2013_gargentas.pdf">Deep dive into Android Binder Framework</a></li><li><a href="https://medium.com/@ledubmurukp/android-system-ipc-mechanisms-3d3b46affa3c">Medium — Android IPC Mechanism</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d724e9d938d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda에서 외부 값을 안전하게 참조하기 (feat. Android Compose)]]></title>
            <link>https://medium.com/@wodbs135/lambda%EB%82%B4%EC%97%90%EC%84%9C-%EC%99%B8%EB%B6%80-%EA%B0%92%EC%9D%84-%EC%8B%A0%EC%A4%91%ED%95%98%EA%B2%8C-%EC%B0%B8%EC%A1%B0%ED%95%98%EA%B8%B0-feat-android-compose-d313900509a0?source=rss-c4377c7a9b52------2</link>
            <guid isPermaLink="false">https://medium.com/p/d313900509a0</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[compose]]></category>
            <dc:creator><![CDATA[Jeremy]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 06:38:17 GMT</pubDate>
            <atom:updated>2024-03-01T06:03:48.000Z</atom:updated>
            <content:encoded><![CDATA[<p>using rememberUpdatedState()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEk3962HyIQVeZvI1Jsq4A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/ko/%EC%82%AC%EC%A7%84/%EB%82%98%EB%AC%B4%EB%A1%9C-%EB%91%98%EB%9F%AC%EC%8B%B8%EC%9D%B8-%EC%88%98%EC%97%AD%EC%9D%98-%EA%B3%A8%EB%93%A0-%EC%95%84%EC%9B%8C-%EC%82%AC%EC%A7%84-eXg_ah-ebc4?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a>-<a href="https://unsplash.com/ko/@photohunter?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Jimmy Chang</a></figcaption></figure><p>Compose를 사용하여 WebView를 구성 하는데에 있어 람다식을 통해 Compose와 상호 작용하면서 문제를 겪게된 케이스를 이야기 하고자 한다.</p><p>아래는 Chrome Android App 화면이다.<br><strong>왼쪽 화면</strong>은 일반적으로 검색으로 볼 수 있는 WebView 화면이며<br><strong>오른쪽 화면</strong>은 왼쪽 화면 오른쪽 상단에 탭 갯수(2)를 클릭 시 볼 수 있는 현재 활성화된 탭과 히스토리로 분류된 탭들이 있는 화면이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MS0kgc7I68CNTEB1Gjj6uw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMjN0vPJriv3PZOGfrqe_g.png" /></figure><p>아래와 같은 개발 조건이 있었다.</p><blockquote>현재 활성화 된 탭을 오른쪽 화면(탭 히스토리)에서 클릭하여 활성화 된 탭을바꿀 수 있으며 해당 탭의 로드가 완료될 때마다 화면을 캡쳐하여 보관하여야 한다.</blockquote><p>문제는 위와 같은 케이스를 개발하다가 발생하였다.</p><p><strong>여러 탭을 스위칭하면서 화면을 캡쳐</strong>하다보니 현재 활성 탭 Id 값과 다른 Id 값으로 저장되어 의도치 않게 <strong>스크린샷(캡쳐)이 맞지 않는 경우</strong>가 발생하였다.</p><p>문제의 코드는 아래와 같았다.</p><pre>@Composable<br>fun SampleWebView(<br>    uiState: MainUiState<br>) = Box(<br>    modifier = Modifier.fillMaxSize()<br>) {<br>    AndroidView(<br>        factory = {<br>            CustomWebView(it).apply {<br>                // 1. 현재 실행 페이지 url 로드<br>                loadUrl(&quot;https://google.com&quot;)<br><br>                // 2. WebViewClient 설정하여 onPageFinished 콜백을 수신 받을 수 있도록 설정<br>                webViewClient = object : WebViewClient() {<br>                    override fun onPageFinished(view: WebView?, url: String?) {<br>                        super.onPageFinished(view, url)<br><br>                        // 3. 페이지 로드가 완료된 시점에 현재 페이지 캡쳐를 위해서 현재 탭 Id 값을 넘겨서 파일 이름 생성에 사용.<br>                        captureImage(uiState.currentTab)<br>                    }<br>                }<br>            }<br>        }<br>    )<br>}<br><br>class CustomWebView constructor(context: Context) : WebView(context) {<br>    fun captureImage(currentTabId: Int) {<br>        // 현재 웹뷰 이미지를 캡쳐하는 로직...<br>    }<br>}</pre><pre>@HiltViewModel<br>class MainViewModel @Inject constructor() : ViewModel() {<br><br>    private val _uiState = MutableStateFlow&lt;MainUiState&gt;(MainUiState())<br>    val uiState: StateFlow&lt;MainUiState&gt; = _uiState<br><br>    init {<br>        viewModelScope.launch {<br>            delay(300) // Network 통신 delay 값 임의 설정<br>            updateTabIdx()<br>        }<br>    }<br><br>    private fun updateTabIdx() { <br>    // 현재 활성 탭을 기본 값에서 활성 탭 id값으로 스위칭 하는 로직<br>        _uiState.update {<br>            it.copy(<br>                currentTab = 1<br>            )<br>        }<br>    }<br>}<br><br>data class MainUiState(<br>    val currentTab: Int = -1<br>)</pre><blockquote>정확하게는 SampleWebView내에 정의되어있는 WebViewClient.OnPageFinished 시점에 uiState.currentTab 값이 계속해서 <br>기본값인 -1로 나오는 문제였다.</blockquote><p>해결 방식은 쉽게 찾을 수 있었지만 이유를 찾는 데에는 시간이 좀 걸렸다.</p><p>위와 같이 최신 값을 계속해서 알고 있어야 하는 경우, Compose에서는 rememberUpdatedState()를 사용하여 최신 값을 읽을 수 있다.</p><pre>@Composable<br>fun &lt;T&gt; rememberUpdatedState(newValue: T): State&lt;T&gt; = remember {<br>    mutableStateOf(newValue)<br>}.apply { value = newValue }</pre><p>rememberUpdatedState의 코드는 위와 같이 작성되어있다.<br>remember를 통해서 Recompose(재구성) 시에도 기억되는 값에 새로운 newValue를 설정해주는 것 뿐이다.</p><pre>@Composable<br>fun SampleWebView(<br>    uiState: MainUiState<br>) = Box(<br>    modifier = Modifier.fillMaxSize()<br>) {<br>    // uiState가 변경될 때마다 recompose에 독립적으로 newState로 바꿀 수 있도록 선언<br>    val newState = rememberUpdatedState(newValue = uiState)<br><br>    AndroidView(<br>        factory = {<br>            CustomWebView(it).apply {<br>                loadUrl(&quot;https://google.com&quot;)<br><br>                webViewClient = object : WebViewClient() {<br>                    override fun onPageFinished(view: WebView?, url: String?) {<br>                        super.onPageFinished(view, url)<br><br>                        // newState를 바라보게 변경<br>                        captureImage(newState.currentTab) <br>                    }<br>                }<br>            }<br>        }<br>    )<br>}</pre><p>위와 같이 변경하면 의도 했던 대로 정확하게 동작하고 있다.</p><p>그럼 여기서 궁금한 점.</p><h4>왜 이전의 state를 참조하고 있었을까?</h4><p>uiState가 변경되어 argument로 전달되면서 recompose가 이뤄지고<br>당연하게도 uiState를 참조하고 있던 곳에서도 새로운 값을 바라 볼 수 있다고 생각하였다.</p><p>이유는 <strong>람다식</strong>에 있었다.</p><p>onPageFinished 람다가 클로저로서 외부의 uiState 변수를 참조하는데, Kotlin의 Closure 동작과 Compose의 Lifecycle 간에 발생하는 시점 차이 때문이다.<br>클로저(closure)는 람다가 정의된 시점의 외부 변수를 캡처한다.<br>캡쳐된 변수는 람다가 호출될 때 사용 되게 된다.</p><p>이는 Compose의 Lifecycle과 관련이 있다. <br>Compose는 상태가 변경될 때마다 재구성(recomposition)을 하게 되는데 <br>이 때, <strong>클로저가 캡처한 변수는 해당 클로저가 정의된 시점에서의 값으로 캡처</strong>가 된다.</p><p><strong>그렇기에 1이 아닌 -1로 캡쳐되어 있었던 것이다.</strong></p><p>따라서 onPageFinished 람다가 클로저로 외부의 uiState 값을 참조하는데, 해당 람다가 정의된 시점에서의 uiState 값이 캡처되기 때문에 최신 값으로 변경되지 않는 것이다.</p><p>클로저에서 캡처된 값은 클로저의 생명 주기 동안 변경되지 않는다.</p><p>그래서 문제가 발생하는 이유는 webViewClient의 onPageFinished 콜백이 외부의 이벤트에 의해 호출되므로, 해당 클로저는 Composable의 라이프사이클과는 독립적으로 동작하는 것이다.</p><p>따라서 SampleWebView가 재구성되더라도 onPageFinished 콜백의 클로저는 이전에 생성된 것을 계속 사용하게 된다.</p><p>좀 더 풀어서 설명하면</p><ol><li>SampleWebView가 처음 호출될 때, WebViewClient 람다 내부의 클로저가 생성되고, 이때의 uiState 값이 캡처된다.</li><li>onPageFinished 콜백은 외부 이벤트에 의해 호출 되며, 이때의 클로저에서는 이미 캡처된 이전의 uiState 값을 사용한다.</li><li>SampleWebView가 재구성되어도 onPageFinished 콜백의 클로저는 이미 생성된 것을 계속 사용하므로, uiState 값이 갱신되지 않는다.</li></ol><p>그래서 <strong>rememberUpdatedState</strong>를 통해 항상 최신 state 값을 바라볼 수 있도록 해야 하는 것이다.</p><h4>rememberUpdatedState를 주의해서 사용해야 하는 점</h4><p>rememberUpdatedState는 콜백이 호출될 때마다 상태를 업데이트 하므로, 해당 콜백이 빈번하게 호출되는 경우에는 성능 상 좋지 않을 수 있다.</p><p>(자주 재구성되는 Compose가 좋다고 말할 수 없기에.)</p><h4>이 문제를 해결하면서 든 의문점</h4><ol><li>왜 Compose Compiler는 Lambda 식을 캡쳐하는가?</li><li>state 변경으로 인해 재구성(recomposition)이 되었는데도 왜 state의 새로운 값을 알지 못하는가?</li></ol><p>Compose에서는 컴포저블 함수 내에서 생성된 <strong>Non-Composable</strong> 람다의 경우, Compile 시점에 <strong>자동으로 remember를 사용하여 wrapping 된다</strong>고 한다. <br>이는 decompile을 통해 확인해 볼 수 있다.</p><pre>// Before compilation<br>val number: Int = 6<br>val lambda = { Log.d(TAG, &quot;number = $number&quot; }<br><br>// After compilation<br>val number: Int = 6<br>val lambda = remember(number) { { Log.d(TAG, &quot;number = $number&quot; } }</pre><p><strong>왜일까?</strong></p><ul><li>이렇게 하면 람다가 생성될 때마다 새로운 인스턴스가 생성되는 것을 방지하고 동일한 람다를 재사용할 수 있게 하기 위한 목적이라고 한다.</li></ul><p>위의 코드는 <a href="https://proandroiddev.com/conscious-compose-optimization-e16144b80eef#039b"><strong>Conscious Compose optimization</strong></a>에서 확인 할 수 있으며 Compose 최적화 관련한 내용을 더 자세히 읽어볼 수 있다.</p><blockquote>그렇다면 <strong>Lambda (클로저)에서 외부 값을 참조</strong>하고 있을 때, 클로저가 생성되는 시점에 외부 값이 캡쳐 된다고 하는데,<br>그렇다면 Composable의 <strong>재구성(recomposition)이 이뤄지더라도 해당 클로저는 재구성</strong>이 되지 않는가?</blockquote><p>위에서 말했듯이, 클로저는 Compose Lifecycle과 독립적으로 동작하며 한 번 생성 될 때, 캡쳐 된 외부 변수를 그대로 사용한다고 하였다.<br>그리고 이는 Compose와 동작할 때, remember로 감싸져 있다면 더욱이 초기 캡쳐 된 초기 값으로 계속 동작하게 된다.</p><p>근데 위에서 Composable 함수 내에 정의된 Non-Composable 람다는 컴파일 시점에 remember로 래핑된다고 했다.</p><p>결국, <strong>Composable 함수 내에 있는 non-composable 람다이기에 외부 변수 값을 참조하는 부분이 처음 캡쳐한 값을 계속해서 갖고 있게 되는 것</strong>이다.</p><p>(그래서 내가 rememberUpdatedState를 사용하여 계속해서 강제적으로 새로운 state를 참조할 수 있게 해준 것이다.)</p><h4>Summary</h4><ul><li>클로저 내부에서 외부 값을 참조하는 상황 그리고 Composable과 결합하여 사용하는 상황이라면 외부 값 참조에 있어서 주의를 기울이며 사용해야 할 것 같다.</li></ul><h4>Reference</h4><ul><li><a href="https://proandroiddev.com/conscious-compose-optimization-e16144b80eef#039b">https://proandroiddev.com/conscious-compose-optimization-e16144b80eef#039b</a></li><li><a href="https://android.googlesource.com/platform/frameworks/support/+/androidx-main/compose/compiler/design/strong-skipping.md">https://android.googlesource.com/platform/frameworks/support/+/androidx-main/compose/compiler/design/strong-skipping.md</a></li><li><a href="https://www.droidcon.com/2022/11/15/understanding-recomposition-performance-pitfalls/">https://www.droidcon.com/2022/11/15/understanding-recomposition-performance-pitfalls/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d313900509a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[실시간 데이터를 캐싱하여 효과적으로 전달하기]]></title>
            <link>https://medium.com/@wodbs135/%EC%8B%A4%EC%8B%9C%EA%B0%84-%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%A5%BC-%EC%BA%90%EC%8B%B1%ED%95%98%EC%97%AC-%ED%9A%A8%EA%B3%BC%EC%A0%81%EC%9C%BC%EB%A1%9C-%EC%A0%84%EB%8B%AC%ED%95%98%EA%B8%B0-d9fe2127002d?source=rss-c4377c7a9b52------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9fe2127002d</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[cache-memory]]></category>
            <dc:creator><![CDATA[Jeremy]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 03:28:00 GMT</pubDate>
            <atom:updated>2023-11-26T06:09:49.886Z</atom:updated>
            <content:encoded><![CDATA[<p>Android Real-time Architecture using cache conception</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JHVTfz2bYufGuQ-8avvJqg.jpeg" /><figcaption><a href="https://unsplash.com/ko/%EC%82%AC%EC%A7%84/%EC%86%90%EC%97%90-%ED%9C%B4%EB%8C%80%ED%8F%B0%EC%9D%84-%EB%93%A4%EA%B3%A0-%EC%9E%88%EB%8A%94-%EC%82%AC%EB%9E%8C-8zcp9L0zNhg">https://unsplash.com/ko/%EC%82%AC%EC%A7%84/%EC%86%90%EC%97%90-%ED%9C%B4%EB%8C%80%ED%8F%B0%EC%9D%84-%EB%93%A4%EA%B3%A0-%EC%9E%88%EB%8A%94-%EC%82%AC%EB%9E%8C-8zcp9L0zNhg</a></figcaption></figure><p>우리는 실시간 성을 가진 데이터를 화면에 보여주기 위해서 Polling, Long Polling, WebSocket 등의 방식을 사용하여 개발한다.</p><p>API 호출로 1회성 통신이 아닌 지속적으로 데이터가 들어오는 경우, 이를 위한 구조가 잘 잡혀 있어야 한다. <br>많은 증권, 코인 서비스들이 실시간 데이터를 위해 WebSocket을 사용하고 있다. (Polling, Long Polling을 사용할 수 도 있다.)</p><p>그럼 안드로이드 앱에서 WebSocket을 사용해서 실시간 데이터를 어떻게 빠르게 화면에 반영할 수 있을까?</p><p>나의 경우, 기존 Polling으로 되어있는 환경에서 WebSocket 방식으로 변경하기 위한 과정에 있었다. <br>해당 과정을 설명하면서 내가 생각하는 실시간 데이터 아키텍쳐를 제시해보고자 한다.</p><h4>Realtime Data Architecture</h4><p>우선, 실시간 데이터 아키텍쳐를 구성하는데에는 여러 고려사항이 있었다.</p><p>일반적으로 데이터를 요청하고 응답 받는 통로가 2가지 일 것이다. <br>Polling일 경우에는 API를 요청하는 부분을 재호출 하여 데이터를 업데이트 하면 될 것이다. (이것은 흔히 보이는 Refresh의 개념과 비슷해 보인다.) <br>물론 이도 해당 아키텍쳐를 따를 수 있다.</p><p>근데 WebSocket을 활용한다면 초기 데이터는 API를 사용하여 구성하고 이후 변경 데이터를 WebSocket으로 받게 될 것이다.</p><p>그렇다면 아래의 의문이 생긴다.</p><blockquote>API와 WebSocket에 동시에 데이터 요청을 해야 할까?</blockquote><p>API와 소켓을 동시에 요청할 경우, API의 응답이 늦어지는데 WebSocket의 응답이 먼저 온다면 100개의 데이터 중 반영된 한 두개만 화면에 보여질 것이다.<br>이후 API 응답이 온 이후에 100개가 그제야 보여질 것이다.</p><p>우리가 원하는 결과는 100개의 데이터를 먼저 보여주고 이 중에서 업데이트가 된 데이터 몇 가지의 내용을 변경해주는 것이다. <br>그래서 API 요청에 대한 응답이 완료되면 그때 WebSocket을 수신하도록 하는 것이 조금 더 안정적으로 데이터를 보여주는 방식일 것이다.</p><blockquote>API를 요청하고 나서 WebSocket을 통해 데이터를 수신한다고 하자.<br>API를 통해 응답 받고 WebSocket 수신을 요청 하였는데 그 찰나에 서버에 새로운 데이터가 생긴다면 해당 데이터는 누락 되는가?</blockquote><p>아래의 그림을 보자.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*0f455YBrXJ7twh4eoGZlGA.jpeg" /><figcaption>Snapshot Necessity</figcaption></figure><p>API를 09시 01분 2초에 요청하였고 9시 1분 2초에 바로 응답을 받았다. <br>9시 1분 3초에 서버에 새로운 데이터가 쌓였고 9시 1분 4초에 소켓 구독을 하였다. <br>그리고 9시 1분 4초에 소켓 데이터를 수신 하였는데 3초 데이터가 아닌 4초 데이터 부터 받을 수 있다.</p><p>위의 예시는 다소 극단적으로 이야기 하였지만 실제로는 초 단위가 아닌 밀리초 단위에서 데이터 수신 차이가 발생할 것이다.</p><p>즉, 누락되게 된다. 네트워크 상황에 따라 충분히 누락이 될 수 있다.</p><p>Ticker와 같이 가장 최신의 데이터만 보여주는 상황이라면 큰 문제가 없을 수 있지만 <strong>호가, 체결 내역 등에 대한 부분을 개발 할 때</strong>에는 네트워크 상황에 따라 해당 로직에서 분명히 데이터 누락이 생길 수 있다.</p><p>9시 1분 2초에 생긴 체결 내역과 9시 1분 4초에 생긴 체결 내역 사이에 데이터가 사라져 버린 것이다.</p><p>그래서 여러 오픈 된 WebSocket 문서를 본다면 데이터 타입을 Snapshot, Realtime으로 나눠서 주는 경우가 있다. <br>이 경우, snapshot으로 기본적인 데이터를 채우고 realtime으로 변경된 데이터를 업데이트 하게 된다.</p><blockquote>Snapshot은 API를 통하지 않고 WebSocket이 연결되었을 때, 그 시점에 DB에 적재된 데이터를 1회성으로 WebSocket을 통해 보내주는 데이터를 의미한다.</blockquote><p>서버의 개발 방향에 따라 달라질 수 있겠지만 Snapshot 데이터가 있다면 이를 활용해서 나쁠 일은 없을 것이다. <br>(하지만, 오늘 내가 소개 할 실시간 데이터 아키텍쳐는 WebSocket Snapshot 방식은 사용하지 않을 예정이다.)</p><blockquote>API를 통해 가져온 데이터 중, WebSocket으로 들어 온 데이터임을 알고 변경하는 작업을 어디서 관리해야 할까?</blockquote><p>처음엔 해당 작업을 ViewModel에서 하려 했다. 물론 명확하게 잘못된 방향이었다.</p><p>무수히 많이 들어오는 데이터를 하나의 ViewModel에서 하기에는 ViewModel의 책임이 너무 많아진다는 생각이 들었으며 데이터를 가공하는 역할을 ViewModel이 하는 게 이상하다고 생각이 들었다.</p><p>또한, 하나의 ViewModel이 아닌 여러 ViewModel에서 데이터 변화를 감지하려면 조금 더 하위 레벨에서 관리되어야 한다고 생각하였다.</p><p>또한, 데이터를 역직렬화하고 기존 데이터와 매핑하여 교체하는 작업을 하기 위해선 Buffer도 필요하고 해당 데이터가 변경 되었음을 명확하게 알려주는 방식도 필요했다.</p><p>이 글의 핵심은 여기서부터 시작된다.</p><p>나의 경우, <strong>Cache라고 하는 데이터 저장소</strong>를 두어 API, WebSocket으로 들어오는 데이터들을 한 곳에서 업데이트하고 이를 방출하여 UI에 신속하게 반영할 수 있도록 하였다.</p><p>쉽게 말해서, Repository에서 Remote(API, WebSocket), Local(DB, DataStore), MemoryCache 로 나뉘어져 데이터를 가져올 때,<br>MemoryCache에 API, WebSocket으로 들어오는 데이터를 동기화하고 Reactive하게 데이터를 읽어오게 만들면서 이를 가능하게 한 것이다.</p><p>아래의 그림으로 보다 명확히 구조를 확인해보자.</p><ol><li>API를 통해 데이터 요청</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*VcY2lNWGu2SqdVctd2Hk8A.jpeg" /></figure><p>2. API를 통해 들어온 데이터를 Cache에 적재</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*lBR7Scxl2O3Y7wnq1NY5UA.jpeg" /></figure><p>3. WebSocket에 데이터 구독 요청</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*wfB9anfrcD2GnxH0fa3yTQ.jpeg" /></figure><p>4. WebSocket을 통해 들어온 데이터 Cache에 적재 (그림)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*qKA8pxcIUy9axyH5WxjHCA.jpeg" /></figure><p>위 과정을 코드로 살펴보자.</p><p><strong>1.</strong> 1번의 요청 과정은 TickerRepositoryImpl에서 getMarketsTicer를 통해API를 요청하는 과정일 것이다.</p><pre>class TickerRepositoryImpl @Inject constructor(<br>    private val marketDataSource: MarketDataSource,<br>    private val tickerCache: TickerCache<br>) : TickerRepository {<br><br>    override suspend fun getMarketsTicker(markets: String): List&lt;MarketCurrencyItem&gt; {<br>        val result = marketDataSource.getMarketsTicker(markets) // 1번 API 요청<br>        result.forEach {<br>            tickerCache.set(it.market, it) // 2번 Cache 적재 과정<br>        }<br>        return result<br>    }<br>     <br>    ...<br>}</pre><p><strong>2.</strong> 2번의 API를 통해 들어온 데이터를 Cache에 적재 작업은 1번에서 받은 응답을 TickerCache에 쌓는 과정이다.</p><p><strong>3.</strong> 1번을 통해 성공 응답을 받은 이후, Cache에서 데이터 변화를 감지하기 위해 파이프라인을 연결한다.</p><p>이는 TickerRepositoryImpl의 getMarketsTickers를 통해 연결한다.</p><pre>interface BaseCache&lt;T&gt; {<br>    val streamFlow: MutableSharedFlow&lt;ConcurrentHashMap&lt;String, T&gt;&gt;<br><br>    val cache: ConcurrentHashMap&lt;String, T&gt;<br><br>    fun flush() {<br>        streamFlow.tryEmit(cache)<br>    }<br><br>    fun set(key: String, data: T) {<br>        cache[key] = data<br>        flush()<br>    }<br><br>    fun clear() {<br>        cache.clear()<br>        streamFlow.tryEmit(cache)<br>    }<br><br>    fun getListFlow(): Flow&lt;List&lt;T&gt;&gt; = streamFlow.conflate().map {<br>        it.values.toList()<br>    }.flowOn(Dispatchers.IO) //straemFlow에서 발생하는 방출을 List 타입으로 가져가겠다.<br>}</pre><p>위와 같은 BaseCache를 두고 getListFlow()로 해당 Flow를 collect하기만 하면 된다.<br>(BaseCache를 구현한 구현체가 TickerCache가 된다.)</p><p><strong>4.</strong> 3번의 웹소켓 데이터 구독 요청은 RealtimeRepositoryImpl에서 requestTickers를 통해 수행한다.</p><pre>class RealtimeRepositoryImpl @Inject constructor(<br>    private val realtimeDataSource: RealtimeDataSource,<br>    private val cacheDataStore: CurrencyCacheDataStore,<br>    private val tickerCache: TickerCache,<br>) : RealtimeRepository {<br><br>    private val internalScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)<br><br>    init {<br>        // 5. WebSocket 이벤트가 발생될 때마다 캐시에 적재<br>        realtimeDataSource.collectUpbitTickers().onEach {<br>            tickerCache.set(it.code, it.mapTo())<br>        }.launchIn(internalScope)<br>    }<br><br>    override fun requestTickers() {<br>        internalScope.launch {<br>            cacheDataStore.upbitCache.map { it.krwMarketCodes }.firstOrNull()?.let { codes -&gt;<br>                val request = listOf(<br>                    RequestTicketField(ticket = UUID.randomUUID().toString()),<br>                    RequestTypeField(<br>                        type = &quot;ticker&quot;,<br>                        codes = codes<br>                    ),<br>                    RequestFormatField()<br>                )<br>                // 4. RealtimeDataSource를 통해 WebSocket에 응답 요청<br>                realtimeDataSource.requestSubscribe(request) <br>            }<br>        }<br>    }<br><br>}</pre><p><strong>5.</strong> 4번의 웹소켓 데이터 수신은 RealtimeRepositoryImpl에서 collect하여 캐시에 데이터를 적재한다.</p><p><strong>6.</strong> 3번에서 연결 해놓은 파이프라인을 통해 5번에서 실시간으로 적재되는 데이터에 따라 화면까지 반영될 수 있다.</p><p>이는 아래 코드에서 getMarketTickers를 UseCase -&gt; ViewModel 경로로 가져가면 UI에 실시간으로 반영될 수 있다.</p><pre>class TickerRepositoryImpl @Inject constructor(<br>    private val marketDataSource: MarketDataSource,<br>    private val tickerCache: TickerCache<br>) : TickerRepository {<br><br>    ...<br><br>    override fun getMarketTickers(): Flow&lt;List&lt;MarketCurrencyItem&gt;&gt; {<br>        return tickerCache.getListFlow()<br>    }<br>}</pre><p><strong>Q. 근데 그러면 Local DB를 사용하면 되지 않을까? Memory Cache가 큰 이점이 있을까?</strong></p><p>DB를 사용하여 1초 안에 여러 번 들어오는 데이터를 계속해서 입출력 하기엔 속도가 매우 느려질 수 밖에 없다. <br>더군다나, 영속적으로 유지되어야 할 필요가 없는 데이터이기에 DB를 쓸 이유도 없다.</p><p>그럼 <strong>Memory Cache</strong>를 사용할 때, 주의 할 점</p><p>실시간으로 엄청 많은 데이터가 인입된다.<br><strong>동기화 문제</strong>를 신경 써야 하기에 java.util.concurrent 패키지 내에 존재하는 자료구조를 사용하여 Thread Safe에 가까워질 수 있다.<br>추가적으로 Mutex를 사용해서 임계 영역에 한 번에 하나만 접근 가능하도록하는 방법도 있을 것이다.</p><h4>Plus Point</h4><p>Cache에서 방출하는 SharedFlow에 Buffer를 두어 수 많은 데이터가 들어오더라도 쌓아둘 수 있도록 하자.<br>하지만 실시간성이 중요하기에 버퍼가 많다고 해서 좋은 것도 아닐 것이다. Buffer를 쌓아두되 정책 상 BufferOverflow.DropOldest로 두는 것을 고려 해 보자.</p><h4><strong>Summary</strong></h4><p>1. API를 통해 데이터 요청 후, 데이터를 Cache에 적재 <br> 2. API 요청 결과에 따라 Cache로부터 Data Pipeline 연결 <br>(Flow로 수신받기 위함) <br> 3. WebSocket에 데이터 구독을 요청 <br> 4. WebSocket을 통해 들어오는 데이터를 활용하여 Cache에 이미 적재된 데이터 중 교체할 데이터를 찾아서 변경 후 방출 <br> 5. 방출된 흐름에 따라 UI에 반영</p><p>실제 프로젝트를 보면서 반영해보자. <br>그리고 다양하고 복잡한 로직을 구현해보며 아키텍쳐를 사용해보자.</p><p>아래의 레포지토리에서 실제로 위의 내용의 구현체를 살펴볼 수 있다.</p><p><a href="https://github.com/jaeyunn15/CryptoApp">GitHub - jaeyunn15/CryptoApp: CryptoCurrency: Data from Upbit, Binance, CoinMarketCap</a></p><p>참고로 WebSocket Library는 ⚡️Thunder를 사용하였다.</p><p><a href="https://github.com/jaeyunn15/Thunder">GitHub - jaeyunn15/Thunder: ⚡️Thunder⚡️ : Android WebSocket library inspired by Scarlet. Support only Coroutine Flow.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9fe2127002d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚡️Thunder: WebSocket have come through the clouds.]]></title>
            <link>https://proandroiddev.com/%EF%B8%8Fthunder-websocket-have-come-through-the-clouds-4db1a9b31ffa?source=rss-c4377c7a9b52------2</link>
            <guid isPermaLink="false">https://medium.com/p/4db1a9b31ffa</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[library-design]]></category>
            <dc:creator><![CDATA[Jeremy]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 09:24:42 GMT</pubDate>
            <atom:updated>2023-09-22T12:55:36.113Z</atom:updated>
            <content:encoded><![CDATA[<p>develop an Android WebSocket library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNPA-gCT3vTC5Rlwtl10Yg.jpeg" /><figcaption><a href="https://unsplash.com/ko/%EC%82%AC%EC%A7%84/5qkGLPikUXM">https://unsplash.com/ko/%EC%82%AC%EC%A7%84/5qkGLPikUXM</a></figcaption></figure><p>As Android app developers, we often develop services that require real-time data.<br>Whether it’s a coin or stock service, there are many situations where data needs to be reflected quickly.</p><p>In this situation, we naturally develop services using a technology called WebSockets.<br>There are many different ways to use WebSockets in Android, and many different libraries.</p><p>Today, I’m going to introduce <strong>Thunder</strong>, a web socket library I develop, and talk about the direction of better real-time services.</p><h3>WebSocket</h3><p>There are a lot of factors to consider when developing a service using WebSockets.</p><p>How to make connections, how to maintain connections, <br>How do you handle network conditions, how do you handle error handling and retry logic, how do you handle asynchronous processing?</p><p>There are too many things to consider to develop it.</p><p>Therefore, simple structure and intuitiveness are important when developing this kind of library.</p><p>From that perspective, <strong>Scarlet</strong>, the Android WebSocket Library I’ve been using in production, has been very handy and provides a lot of functionality.</p><h3>Scarlet</h3><p><a href="https://github.com/Tinder/Scarlet">Scarlet</a> is a library that manages state internally through a state machine and provides a number of features that make using WebSockets on Android very convenient.</p><p>I think it’s worth explaining some of Scarlet’s distinctive features so that you can better understand Thunder, which we’ll talk about later.</p><p><strong>1.WebSocket Event Pipeline</strong></p><p>As a Retrofit-inspired library, it uses the Dynamic Proxy feature to implement its own WebSocket Event pipeline generation logic based on annotations.</p><p>As I understand it, Scarlet is a library that allows you to react reactively to everything that happens to a WebSocket Connection, from opening to closing, by creating a pipeline called a Stream.</p><pre>@Send<br>fun request(request: BinanceRequest)<br><br>@Receive<br>fun observeEvent(): ReceiveChannel&lt;WebSocket.Event&gt;<br><br>@Receive<br>fun observeTicker(): ReceiveChannel&lt;TickerResponse&gt;</pre><p>Simply attach a Send or Receive annotation to the interface as shown above, and it will create a web socket connection internally and create a pipeline to serialize and map the data flowing to Binary and String based on the specific return type and annotation.</p><p>When I first understand this logic, I think that this is a fancy library.</p><p><strong>2.Retries based on connection status</strong></p><p>Once a WebSocket connection is opened, messages are sent and received between the server and client.<br>What if the state of the WebSocket changes due to an error or other circumstances?</p><p>Scarlet has made it possible to retry each time the connection is recreated with the code below.</p><pre>webSocketService.observeEvent() // ReceiveChannel&lt;WebSocket.Event&gt;<br>        .receiveAsFlow()<br>        .filter { it is WebSocket.Event.OnConnectionOpened&lt;*&gt; }<br>        .onEach {<br>            webSocketService.request(BinanceRequest()) // send message (It seems like retry automatically)<br>        }.collect()<br>}</pre><p>In the code above, we’re getting the status of Scarlet’s WebSocket.Event through the observeEvent() method, and we’re making sure that we only send the request when the status is OnConnectionOpened.</p><p>That is the point, we can retry whenever state(WebSocket.Event) of WebSocket is change.</p><p>These are just two of Scarlet’s key points that I focused on while building Thunder, but there are plenty of other features that make it unique, and we hope you’ll try out the library to get a feel for them.</p><h4>So why did I create Thunder?</h4><p>First, a library called Scarlet was developed using Dynamic Proxy, and I was curious about how it creates pipelines, so <strong>I wanted to try my own approach</strong>.<br>(Of course, a lot of this is inspired by Scarlet’s structure.)</p><p>Secondly, there were <strong>some inconveniences or improvement points</strong> that I felt when I used Scarlet in real production, and I tried to improve them by implementing them myself.</p><h3>Thunder</h3><p>Thunder is a WebSocket library based on OkHttp, and it’s a direct implementation of some of the improvements I’ve noticed while writing Scarlet.</p><p>Below, I’ll discuss some of the things I’d like to see improved in Scarlet, using different situations as examples.</p><h4>What if you want to wait until the state of the WebSocket is valid before making a request?</h4><p>By default, Scarlet provides an observeEvent() method that allows you to send a WebSocket request when a WebSocket is connected.<br>(This is the second feature of Scarlet mentioned above.)</p><h4>Question</h4><blockquote>But what if the user’s device loses network connectivity and needs to switch tabs and screens to request new socket data?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*QlW3lHta_DFvj0frrRVPLw.jpeg" /><figcaption><a href="https://www.pxfuel.com/ko/desktop-wallpaper-kypte">https://www.pxfuel.com/ko/desktop-wallpaper-kypte</a></figcaption></figure><p>We have the same screen as above, but the socket data we want is different in the two screens.<br>The left screen requires <strong>socket data for multiple coins</strong>, while the right screen only requires <strong>socket data for Ethereum</strong>.</p><p>If you clicked on Ethereum in the list on the left in the event of a network loss, you will be taken to Ethereum’s detail page, but there is no guarantee that you will be able to request socket data.</p><p>Then, after some time, when the <strong>network is back up and running, you’ll need to re-request the socket data. ⚡️</strong></p><p>Even if you’re back on the network, if you sent websocket data requests before you were connected, they will be invalidated.</p><p>This means that the user needs to know when they have a network connection and resend the request. <br>(I’ve had to work this out in real production).</p><p>So for our team, we actually found a library that had the ability to not spill data downstream based on state in the logic that was requesting the socket data upstream, and we were able to use that to solve the problem.<br>(I think <a href="https://medium.com/@scottalancooper/pausing-and-resuming-a-stream-in-rxjava-988a0977b771">this library</a> is very useful like this kind of situation.)</p><p>Thunder was developed to build in these features and implemented <strong>ValveCache</strong>.</p><pre>class ValveCache(<br>    scope: CoroutineScope<br>) {<br>    private val isEmissiable = MutableStateFlow&lt;Boolean&gt;(true)<br><br>    private val innerQueue = ConcurrentLinkedQueue&lt;Pair&lt;String,String&gt;&gt;()<br><br>    private fun cacheFlow(): Flow&lt;List&lt;String&gt;&gt; {<br>        return flow {<br>            while (currentCoroutineContext().isActive) {<br>                if (isEmissiable.value &amp;&amp; innerQueue.isNotEmpty()) {<br>                    val emitCacheList = mutableListOf&lt;String&gt;()<br>                    while (innerQueue.isNotEmpty()) {<br>                        innerQueue.poll()?.let { emitCacheList.add(it.second) }<br>                    }<br>                    emit(emitCacheList)<br>                }<br>                delay(300)<br>            }<br>        }<br>    }<br><br>    fun onUpdateValveState(state: ThunderState) {<br>        isEmissiable.update { state == ThunderState.CONNECTED }<br>    }<br><br>    fun requestToValve(request: Pair&lt;String, String&gt;) {<br>        innerQueue.add(request)<br>    }<br><br>    fun emissionOfValveFlow(): Flow&lt;List&lt;String&gt;&gt; = cacheFlow()<br><br>    class Factory(<br>        private val scope: CoroutineScope<br>    ) {<br>        fun create(): ValveCache {<br>            return ValveCache(scope)<br>        }<br>    }<br>}</pre><p>Depending on the ThunderState, we are caching all incoming requests (reqeustToValve) until we reach Connected, and then we can emit them downstream if the ThunderState reaches Connected.</p><p>The idea is to collect the flow returned by the emissionOfValveFlow() method so that you can adjust the valve.</p><h4>What if you want request retries to be handled regardless of the state of the WebSocket?</h4><p>Scarlet subscribes to WebSocket.Event so that it can only be requested when OnConnectionOpen, so you need to implement that the user can only make requests when they are in that state.<br>(This is the second feature of Scarlet mentioned above.)</p><p>But with Scarlet, I was hoping that the library would take care of that for me, rather than me having to make adjustments based on the internal state of the library.</p><h4>Question</h4><blockquote>So how can we cache the last socket request and retry it?</blockquote><p>In Thunder, we implemented <strong>RecoveryCache</strong> to handle retries.</p><pre>init {      <br>        combine(<br>            _socketState,<br>            valveCache.emissionOfValveFlow()<br>        ) { currentState, request -&gt;<br>            when (currentState) {<br>                ThunderState.IDLE -&gt; Unit<br>                ThunderState.CONNECTING -&gt; // connecting work<br>                ThunderState.CONNECTED -&gt; {<br>                    if (_lastSocketState is ThunderState.ERROR &amp;&amp; recoveryCache.hasCache()) {<br>                        // Last State : ERROR - this is recovery for socket, network error<br>                        recoveryCache.get().forEach(::requestSendMessage)<br>                        recoveryCache.clear()<br>                    } else {<br>                        // General State<br>                        request.forEach(::requestSendMessage)<br>                    }<br>                }<br>                ThunderState.DISCONNECTING -&gt; // disconnectin work<br>                ThunderState.DISCONNECTED -&gt; // disconnected work<br>                is ThunderState.ERROR -&gt; // error work<br>            }<br>        }.launchIn(scope)<br>    }</pre><p>The code above is Thunder’s way of determining which requests to handle based on the state of the ThunderState.</p><pre>private fun requestSendMessage(message: String) {<br>        if (socket.send(message)) {<br>            recoveryCache.set(message)<br>        }<br>    }</pre><p>It’s the requestSendMessage method that actually sends the message over the websocket.</p><p>It sends the event internally and then stores the request in the recoveryCache based on its success.</p><p>And in the request flow (init block), the request data flowing down from the valve is processed according to the ThunderState.</p><p>In the Connected state, if the previous state is Error and the recoveryCache is not empty, the data that was previously requested is assumed to be in an error state and retried again.</p><p>This eliminates the need for the user to engage in state control, as the last internally cached request is retried even if the network is lost and reconnected.</p><h4>Better real-time service orientation</h4><p>The purpose of Scarlet and Thunder is to have a reactive flow and internally create a pipeline to safely deliver socket data to the data layer.</p><p>As I’ve gotten to know Scarlet and developed Thunder from scratch, I’ve been thinking a lot about where to focus my efforts on real-time socket handling.</p><p>A variety of techniques are used to process and reflect the large amount of data coming in quickly.</p><ol><li><strong>Cache &amp; Buffer &amp; Buffer Flow Strategy</strong></li></ol><pre>Channel&lt;WebSocketEvent&gt;(capacity = 100, onBufferOverflow = BufferOverflow.DROP_OLDEST)</pre><p>In general, backpressure is a phenomenon that occurs when the data is slower to come in than it is to go out, which is why you need to cache it with buffers and adopt a caching strategy.<br><br>There are Flowable in RxJava, Channel, SharedFlow that has Cache in Coroutine.</p><p>We need to make good use of their caching strategy, discarding the oldest data first and reflecting the most recent data well.</p><p>2. <strong>Reactive Flow &amp; Observe &amp; Collect</strong></p><pre>override fun collectEvent(): Flow&lt;WebSocketEvent&gt; {<br>    return channel.receiveAsFlow()<br>}<br><br>override suspend fun onEventDelivery(event: WebSocketEvent) {<br>    channel.trySendBlocking(event)<br>}</pre><p>The concept of Publisher and Subscribe in Scarlet and Channel Send and Flow Collect in Thunder are used to achieve reactive flows.</p><p>This is where we realize the importance of creating and internally implementing proper pipelines to keep the data flowing quickly.</p><p>3. <strong>Robustness &amp; Stability</strong></p><pre>init {<br>    networkState.networkStatus.onEach {<br>        when (it) {<br>            NetworkState.Available -&gt; {<br>                _socketState.updateThunderState(ThunderState.CONNECTING)<br>                openConnection()<br>            }<br>            NetworkState.Unavailable -&gt; {<br>                _socketState.updateThunderState(ThunderState.ERROR(ThunderError.NetworkLoss(null)))<br>                closeConnection()<br>            }<br>        }<br>    }.launchIn(scope)<br><br>    _events.onEach {<br>        when (it) {<br>            is WebSocketEvent.OnConnectionOpen -&gt; {<br>                _socketState.updateThunderState(ThunderState.CONNECTED)<br>            }<br>            is WebSocketEvent.OnMessageReceived -&gt; Unit<br>            WebSocketEvent.OnConnectionClosed -&gt; {<br>                _socketState.updateThunderState(ThunderState.DISCONNECTED)<br>            }<br>            is WebSocketEvent.OnConnectionError -&gt; {<br>                _socketState.updateThunderState(ThunderState.ERROR(ThunderError.SocketLoss(it.error)))<br>            }<br>        }<br>    }.launchIn(scope)<br><br>    combine(<br>        _socketState,<br>        valveCache.emissionOfValveFlow()<br>    ) { currentState, request -&gt;<br>        when (currentState) {<br>            ThunderState.IDLE -&gt; Unit<br>            ThunderState.CONNECTING -&gt; // connectin work<br>            ThunderState.CONNECTED -&gt; // connected work<br>            ThunderState.DISCONNECTING -&gt; // disconnectin work<br>            ThunderState.DISCONNECTED -&gt; // disconnected work<br>            is ThunderState.ERROR -&gt; // error work<br>        }<br>    }.launchIn(scope)<br>}</pre><p>ThunderState has six states, changes states based on a number of external factors, and configures actions to be taken based on the state.<br>Scarlet is much more complex and more robust.<br>(Thunder needs to work harder.)</p><p>Various states and requests change rapidly due to the network environment, user churn, fast screen switching, etc. and need to be responded to appropriately.</p><h4>How to use Thunder</h4><ol><li>Create Thunder Instance</li></ol><pre>@Provides<br>@Singleton<br>fun provideSocketService(<br>    okHttpClient: OkHttpClient,<br>    @ApplicationContext context: Context<br>): SocketService {<br>    return Thunder.Builder()<br>        .webSocketCore(okHttpClient.makeWebSocketCore(&quot;wss://fstream.binance.com/stream&quot;))<br>        .setApplicationContext(context)<br>        .build()<br>        .create()<br>}</pre><p>2. Make request what you want.</p><pre>fun requestAllMarket() { // sear all market data<br>    service.request(request = BinanceRequest(params = listOf(&quot;!markPrice@arr&quot;)))<br>}</pre><p>3. Observe requested data and be sure to view in UI.</p><pre>fun observeAllMarket() {<br>    service.observeAllMarkets().onEach {<br>    <br>    }.launchIn(viewModelScope)<br>}</pre><p>4. Let’s test well.<br>- Try randomly disconnecting and reconnecting to the network.<br>- Move around the screen between tabs to make sure you’re requesting the right data.<br>- and so on…</p><h4>Additional improvement points in Thunder</h4><ol><li>An easy way to handle background/foreground transitions in your app.</li></ol><pre>// this is compose case<br>OnLifecycleEvent { _, event -&gt;<br>    if (event == Lifecycle.Event.ON_RESUME) {<br>        viewModel.requestAllMarketTicker()<br>    }<br>    if (event == Lifecycle.Event.ON_PAUSE) {<br>        viewModel.requestCancelAllMarketTicker()<br>    }<br>}</pre><p>We need our app to make or cancel data requests in the background/foreground. <br>Therefore, code like the above will go into every screen. (compose version)<br>We need to think of a way for the library to handle this.</p><p>2. Support STOMP protocol</p><p>Scarlet also supports STOMP in version 0.2.x, but I don’t think it’s official. <br>I don’t really have a way to test it properly.<br>(I could be wrong about this).</p><p>In Thunder, I want to make it easier for more users to attach websockets by supporting the STOMP method.</p><p>Give us some feedback on the Thunder library after you’ve had a chance to try it out.<br>It’s not as robust as Scarlet, but it can have its moments of usability.<br>If you have more great ideas for the Android WebSocket Library, please let us know.</p><p>Thunder Github : <a href="https://github.com/jaeyunn15/Thunder">https://github.com/jaeyunn15/Thunder</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4db1a9b31ffa" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/%EF%B8%8Fthunder-websocket-have-come-through-the-clouds-4db1a9b31ffa">⚡️Thunder: WebSocket have come through the clouds.</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚡️Thunder: Android WebSocket Library 재구성하기]]></title>
            <link>https://medium.com/@wodbs135/%EF%B8%8Fthunder-websockets-have-come-through-the-clouds-53224f330f9b?source=rss-c4377c7a9b52------2</link>
            <guid isPermaLink="false">https://medium.com/p/53224f330f9b</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[scarlet]]></category>
            <dc:creator><![CDATA[Jeremy]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 15:43:35 GMT</pubDate>
            <atom:updated>2023-09-17T12:32:13.984Z</atom:updated>
            <content:encoded><![CDATA[<p>develop an Android WebSocket library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNPA-gCT3vTC5Rlwtl10Yg.jpeg" /><figcaption><a href="https://unsplash.com/ko/%EC%82%AC%EC%A7%84/5qkGLPikUXM">https://unsplash.com/ko/%EC%82%AC%EC%A7%84/5qkGLPikUXM</a></figcaption></figure><p>안드로이드 개발을 하다보면 실시간 서비스를 개발해야 하는 경우가 있다.<br>코인 시장도 주식 시장도 모두 아주 빠르게 사용자들에게 정확한 데이터를 보여줘야 한다. (라이브 스트리밍도 마찬가지일 것이다.)</p><p>이러한 상황에서 실시간성 서비스를 개발할 때, 우린 WebSocket 이라고 부르는 기술을 사용해서 개발해야 한다.<br>안드로이드에서는 WebSocket을 사용하는 다양한 방법들이 있고 또 다양한 라이브러리들이 있다.</p><p>오늘은 내가 만든 웹소켓 라이브러리인 <strong>Thunder</strong>를 소개하면서 더 나은 실시간 서비스의 방향을 이야기 해보고자 한다.</p><h3>WebSocket</h3><p>WebSocket 관련 서비스를 개발하려면 고려해야 할 요소가 매우 많다.</p><p>어떻게 Connection을 맺을 것인지, 어떻게 Connection을유지할 것인지, <br>네트워크 환경 상태에 따라 어떻게 처리할 것인지, 에러 처리 및 재시도 로직을 어떻게 처리할 것인지, 비동기 처리를 어떻게 처리 할 것인지?</p><p>생각해봐야 할 요소가 매우 많다.</p><p>이를 쉽게 관리해주는 것도 중요하고 쉽게 이해하고 쓸 수 있게 직관적으로 만드는 것도 중요하다.</p><p>그런 포인트에서 내가 실제 프로덕트에서 사용해봤던 Android WebSocket Library인 <strong>Scarlet</strong>은 매우 편리하게 많은 기능을 제공해주었다.</p><h3>Scarlet</h3><p><a href="https://github.com/Tinder/Scarlet">Scarlet</a>은 내부적으로 State Machine을 통해 상태 관리를 하며 Android에서 WebSocket을 매우 편리하게 이용할 수 있게 다양한 기능을 제공해주는 라이브러리이다.</p><p>내가 집중한 Scarlet의 특징적인 기능을 몇 가지 설명해야 Thunder에 대한 이해가 더 쉬울 것 같다.</p><p><strong>1.WebSocket Event Pipeline</strong></p><p>Retrofit에서 영감을 받은 라이브러리답게 Dynamic Proxy 기능을 사용하여 Annotation을 기반으로 WebSocket Event 파이프라인 생성 로직을 자체적으로 구현한다.</p><p>내가 이해한 Scarlet은 WebSocket Connection 연결부터 종료까지 모든 상황을 Stream이라고 하는 Pipeline을 생성하여 Reactive하게 반응할 수 있도록 구현한 라이브러리이다.</p><pre>@Send<br>fun request(request: BinanceRequest)<br><br>@Receive<br>fun observeEvent(): ReceiveChannel&lt;WebSocket.Event&gt;<br><br>@Receive<br>fun observeTicker(): ReceiveChannel&lt;TickerResponse&gt;</pre><p>위와 같이 Send, Receive Annotation을 붙이기만 하면 내부적으로 웹소켓 연결을 만들고 파이프라인을 생성해서 특정 Return Type 과 Annotation을 기반으로 Binary, String으로 흘러오는 데이터들을 직렬화하여 매핑 시켜 준다.</p><p>처음 이 과정을 이해했을 때, 정말 재밌는 라이브러리라고 생각했다.</p><p><strong>2.연결 상태에 따른 재시도</strong></p><p>WebSocket은 Connection이 오픈되면 메세지를 서로 주고받게 되는데 이때, 에러 혹은 다른 상황에 의해 상태가 변화하게 된다면 어떻게 처리해야 할까?</p><p>Scarlet은 아래와 같은 코드를 통해 Connection이 다시 생성 될 때 마다 재시도를 할 수 있게 만들어 주었다.</p><pre>webSocketService.observeEvent() // ReceiveChannel&lt;WebSocket.Event&gt;<br>        .receiveAsFlow()<br>        .filter { it is WebSocket.Event.OnConnectionOpened&lt;*&gt; }<br>        .onEach {<br>            webSocketService.request(BinanceRequest()) // send message (재시도가 알아서 되는 부분)<br>        }.collect()<br>}</pre><p>위의 코드 그대로 observeEvent()를 통해 내부적으로 구현된 WebSocket.Event의 상태를 받아오게 되고 OnConnectionOpened일 때만 요청을 날릴 수 있도록 한다.</p><p>내부적으로 WebSocket Event의 상태를 계속 관찰하며 이를 통해 재시도 할 수 있게 만들어준다는 부분이 포인트이다.</p><p>Thunder에서 집중한 위 2가지 포인트 이외에도 충분히 특징적인 기능들이 많으니 직접 라이브러리를 사용해보며 느껴봤으면 좋겠다.</p><h4>그럼 내가 왜 Thunder를 만들었을까?</h4><p>첫 째는, Scarlet이라는 라이브러리는 Dynamic Proxy를 사용하여 개발되었으며 파이프라인을 생성하는 방식이 궁금하여 <strong>나만의 방식</strong>으로 만들어 보고자 하였다.<br>(물론, 많은 부분에서 Scarlet의 구조를 참고하였다.)</p><p>두 번째는, Scarlet을 실제 프로덕트에 사용해보니 느꼈던 <strong>불편함 혹은 개선 포인트</strong>들이 있었고 이를 직접 구현해서 개선해보고자 하였다.</p><h3>Thunder</h3><p>Thunder는 OkHttp 기반의 WebSocket 라이브러리이며 Scarlet을 쓰면서 내가 느낀 개선 포인트들을 직접 구현해 본 라이브러리이다.</p><p>아래의 상황을 예시로 내가 Scarlet에서 개선하고자 한 포인트들을 이야기 하고자 한다.</p><h4>WebSocket의 상태가 유효할 때까지 기다렸다가 요청하길 원한다면?</h4><p>Scarlet은 기본적으로 WebSocket이 연결된 상태일 때, WebSocket 요청을 보낼 수 있도록 observeEvent() 방식의 메소드를 제공해준다. <br>(위에서 Scarlet의 특징적인 기능 2번째에 언급한 부분이다.)</p><h4><strong>Question</strong></h4><blockquote>근데 만약, 사용자의 단말기의 네트워크가 유실된 상황에서 탭 전환, 화면 전환을 하여 새로운 소켓 데이터 요청을 해야 한다면 어떨까?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*QlW3lHta_DFvj0frrRVPLw.jpeg" /><figcaption><a href="https://www.pxfuel.com/ko/desktop-wallpaper-kypte">https://www.pxfuel.com/ko/desktop-wallpaper-kypte</a></figcaption></figure><p>위와 같은 화면이 있고 두 화면에서 원하는 소켓 데이터는 다르다.<br>왼쪽 화면에선 <strong>여러 코인의 정보를 받는 소켓 데이터</strong>가 필요한 반면, 오른쪽 화면은 <strong>이더리움에 대한 소켓 데이터</strong>만 필요하다.</p><p>네트워크가 유실된 상황에서 왼쪽 화면에서 리스트 중, 이더리움을 클릭 했다면 이더리움의 상세 페이지로는 갔지만 소켓 데이터 요청을 했는지는 모른다.</p><p>그리고 얼마 시간이 지난 뒤, <strong>네트워크가 다시 정상적으로 되었을 때, 소켓 데이터를 재요청 해야 한다.</strong></p><p>다시 네트워크가 연결된 상황이더라도 네트워크 연결되기 이전에 웹소켓 데이터 요청을 보낸 것이라면 그것들은 무효화 되게 된다.</p><p>즉, <strong>사용자는 네트워크 연결이 된 시점을 알고 다시 요청을 보내야 한다는 것이다.</strong> (이것을 나는 실제 프로덕트에서 해결해야만 했다.)</p><p>그래서 우리 팀의 경우, 실제로 데이터를 요청 하는 로직에서 Up Stream에서 상태에 따라 Down Stream에 데이터를 흘려보내지 않는 라이브러리를 찾았고 이를 통해 문제를 해결할 수 있었다.<br>(<a href="https://medium.com/@scottalancooper/pausing-and-resuming-a-stream-in-rxjava-988a0977b771">해당 라이브러리</a>는 이러한 상황에 참 유용할 것 같다.)</p><p>Thunder는 이러한 기능을 내장하기 위해 개발하였고 <a href="https://github.com/jaeyunn15/Thunder/blob/main/thunder/src/main/java/com/jeremy/thunder/cache/ValveCache.kt"><strong>ValveCache</strong></a>를 구현하였다.</p><pre>class ValveCache(<br>    scope: CoroutineScope<br>) {<br>    private val isEmissiable = MutableStateFlow&lt;Boolean&gt;(true)<br><br>    private val innerQueue = ConcurrentLinkedQueue&lt;Pair&lt;String,String&gt;&gt;()<br><br>    private fun cacheFlow(): Flow&lt;List&lt;String&gt;&gt; {<br>        return flow {<br>            while (currentCoroutineContext().isActive) {<br>                if (isEmissiable.value &amp;&amp; innerQueue.isNotEmpty()) {<br>                    val emitCacheList = mutableListOf&lt;String&gt;()<br>                    while (innerQueue.isNotEmpty()) {<br>                        innerQueue.poll()?.let { emitCacheList.add(it.second) }<br>                    }<br>                    emit(emitCacheList)<br>                }<br>                delay(300)<br>            }<br>        }<br>    }<br><br>    fun onUpdateValveState(state: ThunderState) {<br>        isEmissiable.update { state == ThunderState.CONNECTED }<br>    }<br><br>    fun requestToValve(request: Pair&lt;String, String&gt;) {<br>        innerQueue.add(request)<br>    }<br><br>    fun emissionOfValveFlow(): Flow&lt;List&lt;String&gt;&gt; = cacheFlow()<br><br>    class Factory(<br>        private val scope: CoroutineScope<br>    ) {<br>        fun create(): ValveCache {<br>            return ValveCache(scope)<br>        }<br>    }<br>}</pre><p>ThunderState에 따라 Connected에 도달하기 전까지 들어오는 모든 요청(reqeustToValve)을 캐싱하고 있다가 ThunderState가 Connected에 도달한다면 Down Stream에 방출 할 수 있도록 해주었다.</p><p>emissionOfValveFlow()를 통해 반환되는 flow를 collect하여 valve 조절을 할 수 있게 되는 것이다.</p><h4>WebSocket의 상태와 상관 없이 요청 재시도가 알아서 되길 원한다면?</h4><p>Scarlet은 WebSocket.Event를 구독하여 OnConnectionOpen인 상태에서만 요청할 수 있게 구성 하였으며 그렇기에 사용자는 그 상태일 때만 할 수 있는 요청이라고 구현해주어야 한다. <br>(위에서 Scarlet의 특징적인 기능 2번째에 언급한 부분이다.)</p><p>근데 나는 Scarlet을 사용하다보니 굳이 라이브러리 내부 상태에 따라 내가 조절 하기보단 라이브러리에서 다 처리해줬으면 하는 바램이었다.</p><h4>Question</h4><blockquote>그러면 마지막 소켓 요청을 어떻게 캐시해두고 재시도 할 수 있을까?</blockquote><p>Thunder에서는<strong> </strong><a href="https://github.com/jaeyunn15/Thunder/blob/main/thunder/src/main/java/com/jeremy/thunder/cache/RecoveryCache.kt"><strong>RecoveryCache</strong></a>를 구현하여 재시도 처리를 할 수 있게 만들었다.</p><pre>init {      <br>        combine(<br>            _socketState,<br>            valveCache.emissionOfValveFlow()<br>        ) { currentState, request -&gt;<br>            when (currentState) {<br>                ThunderState.IDLE -&gt; Unit<br>                ThunderState.CONNECTING -&gt; // connecting work<br>                ThunderState.CONNECTED -&gt; {<br>                    if (_lastSocketState is ThunderState.ERROR &amp;&amp; recoveryCache.hasCache()) {<br>                        // Last State : ERROR - this is recovery for socket, network error<br>                        recoveryCache.get().forEach(::requestSendMessage)<br>                        recoveryCache.clear()<br>                    } else {<br>                        // General State<br>                        request.forEach(::requestSendMessage)<br>                    }<br>                }<br>                ThunderState.DISCONNECTING -&gt; // disconnectin work<br>                ThunderState.DISCONNECTED -&gt; // disconnected work<br>                is ThunderState.ERROR -&gt; // error work<br>            }<br>        }.launchIn(scope)<br>    }</pre><p>위의 코드는 Thunder 내부에서 ThunderState 상태에 따라 어떠한 요청을 처리할 지 결정하는 코드이다.</p><pre>private fun requestSendMessage(message: String) {<br>        if (socket.send(message)) {<br>            recoveryCache.set(message)<br>        }<br>    }</pre><p>실제로 웹소켓을 통해 메세지를 보내는 곳은 requestSendMessage이다.<br>내부에서 이벤트를 보내고 나서 성공 여부에 따라 recoveryCache에 요청을 저장한다.</p><p>그리고 요청에 대한 흐름(init block)에서는 valve로부터 흘러 내려오는 요청 데이터를 ThunderState에 따라 처리하게 되는데 <br>Connected 상태일 때, 이전 상태가 Error이고 recoveryCache가 있다면 이전에 데이터를 날렸으나 에러로 간 상태라고 간주하여 다시금 재시도 처리를 하게 된다.</p><p>이를 통해, 네트워크가 끊겼다가 다시 붙더라도 내부적으로 마지막 요청을 캐싱한 것을 다시 시도하기 때문에 사용자가 State Control에 관여할 필요가 없어진다.</p><h4>더 나은 실시간 서비스 방향성</h4><p>Reactive한 흐름을 갖고 내부적으로 파이프라인을 생성해서 소켓 데이터를 안전하게 data layer 에 전달하는 것이 Scarlet, Thunder의 목적이다.</p><p>내가 Scarlet을 파악하며 새로이 Thunder를 개발하다보니 실시간 소켓 처리에 어떤 부분에 힘을 주고 개발해야 하는지 생각이 많아졌다.</p><p>수 많은 데이터가 들어오더라도 빠르게 처리되고 반영되어야 하기에 다양한 기술들이 사용된다.</p><ol><li><strong>Cache &amp; Buffer &amp; Buffer Flow Strategy</strong></li></ol><pre>Channel&lt;WebSocketEvent&gt;(capacity = 100, onBufferOverflow = BufferOverflow.DROP_OLDEST)</pre><p>흔히, 배압 현상이라고 하여 데이터를 내보내는 곳보다 데이터를 받아 처리하는 곳의 속도가 느릴 때를 말하는데 이때 이를 버퍼를 두어 캐싱하고 캐싱 전략을 택해야 한다.<br>RxJava에는 Flowable이 있고 Coroutine에는 Channel, SharedFlow 등이 Cache를 가질 수 있다.</p><p>우린 이것을 잘 활용하여 가장 오래된 데이터부터 버려가며 최신 데이터를 잘 반영해야 한다.</p><p>2. <strong>Reactive Flow &amp; Observe &amp; Collect</strong></p><pre>override fun collectEvent(): Flow&lt;WebSocketEvent&gt; {<br>    return channel.receiveAsFlow()<br>}<br><br>override suspend fun onEventDelivery(event: WebSocketEvent) {<br>    channel.trySendBlocking(event)<br>}</pre><p>Scarlet에선 Publisher, Subscribe의 개념으로 Thunder에선 Channel Send, Flow Collect의 조합으로 Reactive한 흐름을 달성하였다.</p><p>수 많은 데이터들이 빠르게 흘러가기 위해선 적절히 파이프라인을 생성하고 내부적으로 구현해주는 것이 중요함을 느끼게 되는 포인트이다.</p><p>3. <strong>Robustness &amp; Stability</strong></p><pre>init {<br>    networkState.networkStatus.onEach {<br>        when (it) {<br>            NetworkState.Available -&gt; {<br>                _socketState.updateThunderState(ThunderState.CONNECTING)<br>                openConnection()<br>            }<br><br>            NetworkState.Unavailable -&gt; {<br>                _socketState.updateThunderState(ThunderState.ERROR(ThunderError.NetworkLoss(null)))<br>                closeConnection()<br>            }<br>        }<br>    }.launchIn(scope)<br><br>    _events.onEach {<br>        when (it) {<br>            is WebSocketEvent.OnConnectionOpen -&gt; {<br>                _socketState.updateThunderState(ThunderState.CONNECTED)<br>            }<br><br>            is WebSocketEvent.OnMessageReceived -&gt; Unit<br><br>            WebSocketEvent.OnConnectionClosed -&gt; {<br>                _socketState.updateThunderState(ThunderState.DISCONNECTED)<br>            }<br><br>            is WebSocketEvent.OnConnectionError -&gt; {<br>                _socketState.updateThunderState(ThunderState.ERROR(ThunderError.SocketLoss(it.error)))<br>            }<br>        }<br>    }.launchIn(scope)<br><br>    combine(<br>        _socketState,<br>        valveCache.emissionOfValveFlow()<br>    ) { currentState, request -&gt;<br><br>        when (currentState) {<br>            ThunderState.IDLE -&gt; Unit<br>            ThunderState.CONNECTING -&gt; // connectin work<br>            ThunderState.CONNECTED -&gt; // connected work<br>            ThunderState.DISCONNECTING -&gt; // disconnectin work<br>            ThunderState.DISCONNECTED -&gt; // disconnected work<br>            is ThunderState.ERROR -&gt; // error work<br>        }<br>    }.launchIn(scope)<br>}</pre><p>ThunderState는 6가지의 상태를 갖고 수 많은 외부 요인에 의해 상태를 바꿔 가며 상태에 따라 취해야 할 동작을 구성한다.<br>Scarlet은 이보다 훨씬 복잡하고 더 견고하게 구성되어 있다.<br>(Thunder는 더 노력해야 한다.)</p><p>네트워크 환경, 사용자의 서비스 이탈, 빠른 화면 전환 등을 통해 여러 상태와 요청이 빠르게 변화하고 이를 적절하게 대응해야 한다.</p><h4>Thunder 사용법</h4><ol><li>Thunder를 생성하자</li></ol><pre>@Provides<br>@Singleton<br>fun provideSocketService(<br>    okHttpClient: OkHttpClient,<br>    @ApplicationContext context: Context<br>): SocketService {<br>    return Thunder.Builder()<br>        .webSocketCore(okHttpClient.makeWebSocketCore(&quot;wss://fstream.binance.com/stream&quot;))<br>        .setApplicationContext(context)<br>        .build()<br>        .create()<br>}</pre><p>2. 원하는 요청을 처리하자</p><pre>fun requestAllMarket() { // 전체 마켓 데이터 조회<br>    service.request(request = BinanceRequest(params = listOf(&quot;!markPrice@arr&quot;)))<br>}</pre><p>3. 요청한 데이터를 관찰하고 화면에 잘 반영하자.</p><pre>fun observeAllMarket() {<br>    service.observeAllMarkets().onEach {<br><br>    }.launchIn(viewModelScope)<br>}</pre><p>4. 테스트를 잘 수행하자<br>- 네트워크를 임의로 끊고 다시 연결해보세요. <br>- 탭 간 이동하면서 데이터를 제대로 요청하는지 확인하세요.<br>- and so on…</p><h4>Additional improvement points in Thunder</h4><ol><li>앱의 백그라운드/포그라운드 전환에 따라 쉽게 처리하는 방법.</li></ol><pre>// this is compose case<br><br>OnLifecycleEvent { _, event -&gt;<br>    if (event == Lifecycle.Event.ON_RESUME) {<br>        viewModel.requestAllMarketTicker()<br>    }<br>    if (event == Lifecycle.Event.ON_PAUSE) {<br>        viewModel.requestCancelAllMarketTicker()<br>    }<br>}</pre><p>우리는 앱이 백그라운드/포그라운드에 따라 데이터 요청을 수행 혹은 취소해야 한다. 그렇기에 위와 같은 코드들이 모든 화면마다 들어갈 것이다.<br>이것을 라이브러리가 해결할 방법을 생각 해봐야 한다.</p><p>2. STOMP protocol 지원</p><p>Scarlet도 <a href="https://github.com/Tinder/Scarlet#update">0.2.x 버전</a>에서 STOMP를 지원한다고 하지만 정식 지원은 아닌 것 같다.. 제대로 테스트 할 방법도 딱히 없다.</p><p>Thunder에선 STOMP 방식을 지원하여 더 많은 사용자가 쉽게 웹소켓을 붙일 수 있게 하고 싶다.</p><p>Thunder를 사용해보고 의견을 알려주세요. <br>Scarlet만큼 견고하진 않지만 때에 따라 사용성이 좋은 부분들이 있을 수 있습니다.<br>Android WebSocket Library에 더 많은 좋은 의견이 있다면 알려주세요.</p><p>Thunder Github : <a href="https://github.com/jaeyunn15/Thunder">https://github.com/jaeyunn15/Thunder</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53224f330f9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test Code가 주는 불편함과 행복]]></title>
            <link>https://medium.com/@wodbs135/test-code%EA%B0%80-%EC%A3%BC%EB%8A%94-%EB%B6%88%ED%8E%B8%ED%95%A8%EA%B3%BC-%ED%96%89%EB%B3%B5-8e96469bad42?source=rss-c4377c7a9b52------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e96469bad42</guid>
            <category><![CDATA[testcode]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jeremy]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 12:10:28 GMT</pubDate>
            <atom:updated>2023-07-02T12:10:28.809Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s pass the Android unit test.</p><figure><img alt="Photo by https://unsplash.com/ko/%EC%82%AC%EC%A7%84/PlBsJ5MybGc" src="https://cdn-images-1.medium.com/max/1024/1*MOm-F2pU795iI8abYtwzxw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/ko/%EC%82%AC%EC%A7%84/PlBsJ5MybGc">https://unsplash.com/ko/%EC%82%AC%EC%A7%84/PlBsJ5MybGc</a></figcaption></figure><p>안드로이드 개발자라면 MVVM, MVI 등 다양한 아키텍쳐를 접해보았을 것이며 Clean Architecture 또한 여러 프로덕트에 이미 적용이 되고 있다. <br>그리고 여러 아키텍쳐가 가지는 장점 중 하나는 테스트 가능한 구조를 만든다는 것이다. 테스트 가능한 구조를 가진다는 것은 무슨 의미일까?</p><p>각 기능을 독립적인 레이어 단위로 구조화하고 이를 <strong>테스트 가능</strong>하게 한다 라고 생각한다.</p><p>근데 정작 나는 아키텍쳐를 도입하면서 제대로 테스트를 수행해 본 경험이 없다. 프로덕트에 적용한 경험이 있지만 이게 맞는지?에 대한 확실함은 없었다.</p><p>해당 글에서는 왜 테스트를 하며 테스트를 어떻게 하여 어떠한 장점을 가져갈 수 있을지 이야기해보고자 한다.</p><h4>우린 왜 테스트 코드를 작성해야 할까?</h4><p>매번 코드를 빌드해서 검증하고 결과를 로그로 찍어보면서 원하는 결과를 테스트 하기보단 코드 레벨에서 작성하고 수정하면 훨씬 편하게 검증할 수 있지 않을까?</p><p>특정 함수가 특정 Input에 대해서 특정 Output이 도출되는지 체크하고 싶다면 어떠한 Input을 넣으면 어떠한 Output이 나올지 예상/실제결과를 적어두고 테스트 코드를 작성하기만 하더라도 충분히 의미 있는 테스트가 될 수 있다고 생각한다. (물론 단순히 성공 케이스만 반환하는 걸 이야기 하는게 아니다.)</p><h4>그럼 어디부터 테스트를 해야 할까?</h4><p>Data Layer, Domain Layer, Presentation Layer 이외 많은 영역과 UI test, 통합 테스트 등도 있다. 테스트를 시작하는 단계라면 단위 테스트를 하는 것만으로도 충분하다고 생각한다.</p><p><strong>과연 단위 테스트가 주는 이점은 무엇일까? (테스트를 왜 해야 할까?)</strong></p><ol><li>코드 변경시 변경 부분에 대한 Side Effect를 파악할 수 있다.</li><li>여러 테스트 커버리지를 작성해두면 나중에 요구사항 변경에 대해서 바꾸게 되더라도 실패하는 테스트를 보고 어떠한 Side Effect가 발생할 지 파악할 수 있다.</li><li>테스트를 작성하기 위해 함수를 테스트 가능한 단위로 분리하게 될 것이고 그렇다면 자연스럽게 가독성 좋은 코드를 작성하게 될 것이다. <br>(그렇지 않을 수도 있다.)</li><li>결국 여러 테스트 케이스를 작성하고 적용해야 나중에 변경 사항을 맞닥뜨리더라도 쉽게 파악할 수 있다. 개인적으로 그때 그때 성공 케이스만 두는 건 의미가 없을 수 있다고 생각한다.</li></ol><h4><strong>그럼 단위 테스트가 왜 어려울까?</strong></h4><ol><li>어떤 부분을 어떻게 테스트 해야 할지 모른다. 나조차 테스트를 처음 접하면서 어느 부분에 대한 테스트를 해야하는 건지 몰랐다.<br>비즈니스 로직부터 하자. Clean Architecture에서 말하는 Domain Layer일 수 있고 MVVM의 ViewModel일 수 있다.</li><li>테스트를 이렇게 수행하는게 맞는가 싶을때가 있다.<br>단위 테스트 예제를 찾으면 Mock, Fake 데이터를 두고 원하는 응답을 그저 반환 하기만 한다. 이게 맞는가? <br>코드 내에 여러 분기 로직이 있을거고 분기점마다 원하는 결과로 잘 빠져서 예상되는 응답 결과를 뱉어내는 것도 의미 있다고 생각한다.</li></ol><h4><strong>그럼 테스트를 어떻게 해야 할까?</strong></h4><p>예제를 갖고 이야기 해보자.</p><p>예제는 검색어를 입력하고 변화하는 검색어에 따른 결과에 대한 테스트를 수행하는 예제이다.</p><p>View에서는 ViewModel의 uiState라고 하는 화면의 상태(StateFlow)를 collect하고 있고 ViewModel의 수행 로직에 따라 uiState(StateFlow)를 업데이트 하게 된다.</p><p>아래는 ViewModel 코드의 일부이며 아래 코드들을 어떻게 테스트 할 수 있을지 알아보자.</p><pre>private val _searchParamState = MutableStateFlow(SearchState(searchQuery = &quot;&quot;)) //검색어를 갖고 있는 StateFlow<br><br>val uiState = _searchParamState<br>    .filter { it.searchQuery.isNotBlank() } //검색어가 비어있는지 검사 수행<br>    .flatMapLatest { searchParamState -&gt;<br>        if (searchParamState.searchQuery.length &lt; 2) {<br>            flowOf(SearchResultUiState.EmptyQuery) // 2. 검색어가 2자리 미만이라면 EmptyQuery가 반환된다.<br>        } else {           <br>            handleResult(searchParamState) // 3. 검색어에 대한 검색 수행<br>        }<br>    }.stateIn(<br>        scope = viewModelScope,<br>        started = SharingStarted.WhileSubscribed(5_000),<br>        initialValue = SearchResultUiState.Wait, // 1. 기본 상태는 Wait이다.<br>    )<br> <br>private fun handleResult(state: SearchState) =<br>        getCharactersUseCase(state.searchQuery, state.offset)<br>            .asResult()<br>            .map { result -&gt;<br>                when (result) {<br>                    is Result.Success -&gt; {<br>                        SearchResultUiState.Success(<br>                            characters = result.data.map(CharacterEntity::toUiModel)<br>                        )<br>                    }<br><br>                    is Result.Error -&gt; {<br>                        SearchResultUiState.LoadFailed(result.exception?.message.orEmpty())<br>                    }<br><br>                    Result.Loading -&gt; {<br>                        SearchResultUiState.Loading<br>                    }<br>                }<br>            }<br><br>fun updateKeyword(keyword: String) = _searchParamState.update {<br>        if (keyword != it.searchQuery) {<br>            it.copy(searchQuery = keyword, offset = 0) //여기서 검색어가 변경된다.<br>        } else {<br>            it<br>        }<br>    }</pre><ol><li><strong>검색어 입력 없이 그냥 화면 진입한 경우</strong></li></ol><p>uiState는 기본 상태를 가질 것이며 initialValue는 SearchResultUiState.Wait이다.<br>이걸 검증하기 위해선 state가 예상 결과 그대로인지 봐야 한다.<br>아래처럼 작성할 수 있을 것이다. 이것 또한 단위테스트의 일부이다.</p><pre>@Test<br>fun `아무 이벤트가 없을 경우, 초기 상태는 Wait`() = coroutineRule.runTest {<br>    assertEquals(SearchResultUiState.Wait, searchResultViewModel.uiState.value)<br>}</pre><p>2. <strong>검색어가 2자리 미만이라면 EmptyQuery라는 상태로 변경될 것이다.</strong></p><p>이 테스트를 수행하기 위해선, 검색어를 업데이트 해야하고 그에 따른 state 변화를 지켜봐야 한다. <br>아래 <strong>(1) 키워드 업데이트</strong>를 통해 flow가 흐르도록 만들고 uiState가 어떻게 변화 되었는지 체크한다.</p><pre>@Test<br>fun `하나의 단어로 키워드를 업데이트 하는 경우, EmptyQuery 상태로 변경`() = coroutineRule.runTest {<br>    val collectJob = launch {<br>        searchResultViewModel.uiState.collect() //특정 StateFlow를 collect하여 변화를 감지한다.<br>    }<br><br>    searchResultViewModel.updateKeyword(&quot;a&quot;) //1. 키워드 업데이트 <br><br>    runCurrent() //예약된 코루틴을 실행<br><br>    assertEquals(SearchResultUiState.EmptyQuery, searchResultViewModel.uiState.value) // 결과 검증<br><br>    collectJob.cancel() // 코루틴 잡 취소 처리<br>}</pre><p>3. <strong>검색어가 2자리 이상이라면 검색을 수행하고 그에 따른 결과로 업데이트 될 것이다.</strong></p><p>우리는 해당 테스트에서도 여러 분기를 나눌 수 있다.<br>- 검색 결과가 일치하는 응답이 있는지?<br>- 검색 결과에 일치하는 응답이 없는지?</p><pre>@Test<br>fun `2개 이상의 단어로 이뤄진 키워드 입력 시, 매칭되는 결과가 있다면 Success 상태와 성공적인 응답 반환`() = coroutineRule.runTest {<br>    val collectJob = launch {<br>        searchResultViewModel.uiState.collect()<br>    }<br><br>    searchResultViewModel.updateKeyword(&quot;xxx&quot;)<br><br>    characterTestRepository.addCharacters(testCharactersData) //1. 반환될 테스트 데이터 추가<br><br>    runCurrent()<br><br>    val result = searchResultViewModel.uiState.value<br><br>    assertIs&lt;SearchResultUiState.Success&gt;(result)<br><br>    assertEquals(3, result.characters.size)<br><br>    collectJob.cancel()<br>}</pre><p>위 코드를 통해 <strong>검색어에 일치하는 검색 결과가 있는 성공 결과</strong>를 테스트 해 볼 수 있다.</p><p>근데 여기서 유심히 봐야 하는 건, <strong>(1) 반환될 테스트 데이터 추가 </strong>하는 부분이다. 저건 왜 존재할까?</p><p>우린 현재 ViewModel에 대한 테스트를 수행하고 있고 ViewModel에선 UseCase를 주입 받아 검색을 수행한다. <br>근데 UseCase는 또 Repository를 주입 받아 검색을 수행한다.</p><p>그래서 Repository에 Fake Data를 넣어서 반환하게 만드는 것이다. 그러면 UseCase를 통해 Fake Data가 흘러올 것이고 이를 ViewModel에서 검증할 수 있다.</p><p>이러한 개념이 Unit Test의 Test Double(테스트 대역)이며 테스트하려는 객체가 다른 여러 객체들과 관계가 엮여있어서 직접적으로 사용하기 힘들 때, 대체할 수 있는 객체를 의미한다.</p><p>내가 지금 테스트 해보고 싶은 건, ViewModel to UseCase 로직이다. 그래서 Repository에서 오는 데이터를 대체할 수 있는 데이터로 흘려보낸 것이다.</p><p>대표적으로 Mock, Stub 등의 개념이 있으며 이는 해당 글에서 다루기엔 너무 방대해질 내용이라 판단되어 <a href="https://tecoble.techcourse.co.kr/post/2020-09-19-what-is-test-double/">잘 정리된 글</a>을 읽어보는 것을 추천드린다.</p><p>테스트로 돌아와서, 테스트 더블을 추가하여 원하는 응답을 반환하여 state가 정상적으로 바뀌었는지 테스트한다. <br>Success 상태로 변화되었는지 체크하고 데이터의 길이 역시 체크한다.<br>어떤 부분을 추가로 체크할 지는 테스트 담당자의 몫이라고 판단된다.</p><p>위는 간단한 예제에 대한 테스트 코드 작성이었다.<br>모든 코드가 위와 같이 테스트가 편한 구조라면 얼마나 좋을까?</p><p>그렇지만 사실 위의 코드는 원래는 아래의 코드와 같이 생겼었다.<br>로딩 상태를 나타내는 uiProgressState를 별도로 갖고 있었다.</p><pre>private val _searchParamState = MutableStateFlow(SearchState(searchQuery = &quot;&quot;)) //검색어를 갖고 있는 StateFlow<br><br>val uiProgressState = MutableStateFlow&lt;Boolean&gt;(false)<br><br>val uiState = _searchParamState<br>    .filter { it.searchQuery.isNotBlank() } //검색어가 비어있는지 검사 수행<br>    .onStart {<br>         uiProgressState.tryEmit(true) // 로딩 상태를 true로 변경<br>    }<br>    .flatMapLatest { searchParamState -&gt;<br>        if (searchParamState.searchQuery.length &lt; 2) {<br>            uiProgressState.tryEmit(false) // 로딩 상태를 false로 변경<br>            flowOf(SearchResultUiState.EmptyQuery) // 2. 검색어가 2자리 미만이라면 EmptyQuery가 반환된다.<br>        } else {           <br>            handleResult(searchParamState) // 3. 검색어에 대한 검색 수행<br>        }<br>    }.stateIn(<br>        scope = viewModelScope,<br>        started = SharingStarted.WhileSubscribed(5_000),<br>        initialValue = SearchResultUiState.Wait, // 1. 기본 상태는 Wait이다.<br>    )<br> <br>private fun handleResult(state: SearchState) =<br>        getCharactersUseCase(state.searchQuery, state.offset)<br>            .asResult()<br>            .map { result -&gt;<br>                when (result) {<br>                    is Result.Success -&gt; {<br>                        SearchResultUiState.Success(<br>                            characters = result.data.map(CharacterEntity::toUiModel)<br>                        )<br>                    }<br><br>                    is Result.Error -&gt; {<br>                        SearchResultUiState.LoadFailed(result.exception?.message.orEmpty())<br>                    }<br>                }<br>            }<br>            .onCompletion {<br>                uiProgressState.tryEmit(false) // 로딩 상태를 false로 변경<br>            }</pre><p>위와 같은 구조라면 데이터를 요청하고 응답 받기 이전에 로딩 상태가 제대로 변경 되었는지 응답 다고 난 이후, 로딩 상태가 제대로 변경 되었는지에 대한 테스트를 추가로 해줘야 한다.</p><p>즉, 관리 포인트가 여러 부분으로 생긴다고 생각된다.</p><p>내가 생각하는 테스트 코드를 작성하면서 <strong><em>좋은 코드가 만들어지는 부분은 이러한 부분(관리 포인트)을 줄이는 것도 그 중 하나</em></strong>라고 생각된다. 코드가 개선이 되는 부분이니까? (물론 이게 절대적인 정답은 아니다.)</p><p>결국, 위에서 적은 테스트 코드 작성에 대한 이점 중 세 번째와 같이 <strong><em>코드의 구조 변경 및 더 괜찮은 방식을 생각해내게 된다는 점</em></strong>을 느낄 수 있다.</p><p>말이 와닿지 않는다면 직접 본인이 작성한 코드의 테스트 코드를 작성해보면 느낄 수 있을 것이다.</p><h4>단위 테스트에 대해 더 생각해봐야 할 점</h4><p>1. 이렇게 단순한 코드까지 테스트할 필요가 있을까?</p><p>정말 단순하게 응답 결과를 전달해주는 정도의 코드라면 굳이라고 생각이 들 수도 있다. 근데 시간이 허락해준다면 해도 괜찮다라고 생각한다. <br>나중에 해당 코드에 어떠한 분기가, 의존성이 생길지 모르기에 테스트 코드를 작성해두고 변경사항에 따라 사이드 이펙트의 정도를 지켜보는 것도 좋다고 생각한다.</p><p>2. 코드를 테스트 하는게 좋은 것은 맞지만 릴리즈 일정, 제품 완료 기한을 넘기면서 까지 할 건 아니다. 비즈니스가 최우선이다.</p><p>3. 테스트 코드를 맹신하지 말자. 몇가지 케이스로 적어둔 테스트 코드가 내 모든 프로덕트의 안정성을 책임져주지 않는다.</p><p>4. 충분히 여러 환경에 대한 테스트가 필요하다.</p><p>단위 테스트 말고도 통합 테스트, UI 테스트도 있다. 안드로이드 앱 개발의 경우, 여러 종류의 디바이스, 네트워크 유실 테스트, LMK에 의해 앱이 재실행 되는 경우, Configuration Change가 되는 경우 등등 다양한 환경에서 실제로 테스트 해볼 건 많다.</p><h3>결론</h3><ul><li>테스트 코드는 미루다보면 계속 미루게 된다. 작은 부분부터라도 조금씩 작성해보자.</li><li>코드 변경 사항에 대해서 어떤 지점들이 영향을 받는지 파악하는 수준과 좋은 아키텍쳐로 분리한다는 것에만 만족해도 충분하다고 생각한다.</li><li>나도 테스트를 제대로 수행하고 있다고 생각하진 않는다. 어떤 방식이든 테스트를 함으로써 얻는 이점은 충분하다 생각한다.</li><li>프로덕트에 대한 안정성을 높이고 싶다면 더 다양한 테스트를 해보자.</li></ul><p>위에 샘플 코드로 첨부된 테스트 코드는 <a href="https://github.com/jaeyunn15/MarvelApp/blob/master/feature/search/src/test/java/com/project/marvelapp/viewmodel/SearchResultViewModelTest.kt">여기서</a> 확인 할 수 있습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e96469bad42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[View Lifecycle에 따라 ViewModel 간 데이터 공유하기]]></title>
            <link>https://medium.com/@wodbs135/view-lifecycle%EC%97%90-%EB%94%B0%EB%9D%BC-viewmodel-%EA%B0%84-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EA%B3%B5%EC%9C%A0%ED%95%98%EA%B8%B0-c6d9dbf2682b?source=rss-c4377c7a9b52------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6d9dbf2682b</guid>
            <dc:creator><![CDATA[Jeremy]]></dc:creator>
            <pubDate>Sun, 05 Mar 2023 14:51:22 GMT</pubDate>
            <atom:updated>2023-03-05T14:52:13.869Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lifecycle에 따라 ViewModel 간 데이터 공유하기</h3><p>Sharing data between ViewModels according to View Lifecycle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C8UXuindShQpeeYyqpsFaA.jpeg" /><figcaption>Photo by https://unsplash.com/ko/%EC%82%AC%EC%A7%84/aW50su5Dwek</figcaption></figure><p>앱 개발을 하다보면 다양한 요구 사항에 따라 여러 화면에서 동일한 데이터를 공유해야 하는 경우가 있다.</p><p>진행 중인 프로젝트에 따라 Single Activity — Multi Fragment인 경우도 있을 것이고 Multi Activity — Multi Fragment인 경우도 있을 것이다.</p><p>이에 따라 Android View의 Lifecycle에 맞게 바라보아야 할 데이터를 잘 관리해주어야 할 것이고 그렇기에 요구사항을 충족할 여러 개발 방법들이 있을 수 있다.</p><p>명확하게 맞는 답을 제시하기 보단 하나씩 더 괜찮은 방법들을 고민해보며 프로젝트에 적용해본 경험을 공유하고자 한다.</p><h4>Activity Lifecycle Scope, Fragment Lifecycle Scope 고려하기</h4><p>Fragment는 Activity의 Lifecycle에 종속된다.</p><p>그렇기에 하나의 Activity 아래에 생성되어 동작하는 Fragment 간에 데이터를 공유하기엔 Activity를 통해서 공유하는 것이 일반적으로 떠오를 수 있는 첫 번째 아이디어이다.</p><p>아래와 같이 Activity에 선언한 이후, 하위 Fragment에서 Activity Scope에 맞는 뷰모델을 사용할 수 있다.</p><pre>class MainActivity : AppCompatActivity() {<br>      ...<br>      private val viewModel: MainViewModel by viewModels()<br>      ...<br>}<br><br><br>class HomeFragment: Fragment() {<br><br>      //hilt<br>      private val mainViewModel: MainViewModel by activityViewModels()<br>      <br>      //koin<br>      private val mainViewModel: MainViewModel by sharedViewModel()<br><br>}</pre><p>근데 위와 같이 작성하면 한 가지 불편한 점이 생길 수 있다.</p><p>예를 들어, 각 Fragment의 ViewModel에서 작업을 수행한 뒤, 나온 결과 값을 다음 프로세스의 Fragment가 활용해야 해서 Activity ViewModel에 각 스탭의 최종 결과 값 만을 업데이트 해야 하는 상황이라고 생각해보자.</p><p>그럼 각 Fragment마다 아래와 같은 코드가 들어갈 것이다.</p><pre>class HomeFragment: Fragment() {<br><br>      override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>          super.onViewCreated(view, savedInstanceState)<br>          <br>          val currentStepValue = viewModel.homeStateFlow.value //Fragment의 Value<br>          mainViewModel.updateData(currentStepValue) //Activity ViewModel에 Value Update<br>      }<br>}</pre><p>이러한 코드들이 Fragment마다 존재해야 한다. Activity Scope를 써야하니 어쩔 수 없는 것일까..</p><p>사실, 위처럼 단순하게 일회성처럼 각 Fragment의 값을 읽어와서 Activity에 전달하는 정도라면 괜찮을 수도 있다.</p><p>근데 만약 반대로 Activity의 특정 값에 따라 종속된 모든 Fragment의 상태가 바뀌어야 한다 라고 한다면 어떨까?</p><pre>class HomeFragment: Fragment() {<br>    <br>    private val activityViewModel: MainViewModel by activityViewModels()<br><br>    private val fragmentViewModel: HomeViewModel by viewModels()<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br><br>        viewLifecycleOwner.lifecycleScope.launch {<br>            repeatOnLifecycle(Lifecycle.State.CREATED) {<br>                launch {<br>                    activityViewModel.mainStateFlow.collect { //Activity에서 값 변화를 읽어와서<br>                        fragmentViewModel.updateValue(it) //Fragment에 값 변화를 전달해야 함.<br>                    }<br>                }<br>            }<br>        }<br>    }  <br>    <br>}</pre><p>위와 같은 코드가 Fragment마다 생성되게 될 것이다.</p><p>이는 Fragment가 늘어날 수 있는 경우, 보일러 플레이트 코드가 늘어날 수 있다.</p><p>그렇다면 위의 문제를 어떻게 해결 할 수 있을까?</p><p>사실 위에서 나열된 문제들의 원인은 <strong>뷰모델 간 데이터 공유</strong>를 뷰를 통해 해결하려고 해서 나온 문제이다.</p><p>물론, 생명주기가 중요한 안드로이드 생태계에서 뷰를 고려하지 않을 수 없다. <br>근데 이를 좀 다른 관점에서 고려해볼 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrpqlJrH0uPBQvmQH1m2JA.png" /></figure><p>계속해서 위에서 말한 부분은 위와 같은 관점이다. Fragment Scope의 뷰모델에서 Activity Scope에 값을 업데이트 한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0dNwGAEjH4Mh80Ka3aRGQ.png" /></figure><p>위의 그림처럼 데이터를 View를 통해 전달하려고만 하니 문제들이 생긴다.</p><p>그래서 View가 아닌 아래처럼 하위 레이어로 전달해보고자 한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2YR33kaIOm0UMyLmR7SkA.png" /></figure><p>바뀐 방식을 보면 뷰를 전혀 통하지 않고 뷰모델 간 데이터를 공유하고 있다.</p><p>그러면 위에서 적게 되었던 Activity ViewModel의 값 변화를 읽어 Fragment ViewModel에 업데이트 해주는 코드를 모두 지우고 뷰모델과 이하 레이어로 바꿀 수 있다.</p><p>그럼 여기서 문제는 SharedDataUseCase를 어떻게 생성해서 어떻게 활용할까?</p><ol><li><strong>Singleton으로 생성해보기(?)</strong></li></ol><p>필자는 UseCase를 Singleton으로 생성해서 사용한 경우가 많이 있었다. 그래서 UseCase를 사용하려고 하다보니 습관적으로 싱글톤으로 생성하였다. 그 당연함이 또 문제를 만들었다.<br>공유되는 데이터는 흐름대로 ParentActivity가 Lifecycle 상 살아있는 동안에만 유효한 데이터 들이다. <br>그렇기에 우리가 위에서 Activity Scope라는 개념을 계속 적용하려 한 것이다.</p><p>싱글톤으로 억지로 만든다면 ParentActivity 의 onDestory()가 호출되는 순간에 SharedDataUseCase에 존재하는 값 들도 nullable하게 만들어줘야 할 것이다. (이렇게까지 싱글톤으로 써야할까..)</p><p>2. <strong>Activity Lifecycle에 맞게 지정해주기</strong></p><p>싱글톤 말고 Activity Lifecycle에 맞게 UseCase를 생성하고 없애고 싶었다.<br>방법이 없을 것 같지가 않아서 찾다보니 있었다.</p><p>사실 여기선 Hilt라는 DI 라이브러리의 개념을 하나 알아야한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*N-EFlGN3A7jRLrHVyc5gAg.png" /></figure><p>Hilt를 공부해본 사람이라면 꼭 한 번 쯤 봤을 Component Hierarchy이다.</p><p>여기서 지금 우리가 중요하게 볼 포인트는 <strong>ActivityRetainedComponent</strong>이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXh-6HXYS0XFCaaJhxiN9w.png" /></figure><p>Android Jetpack 문서에 <a href="https://developer.android.com/training/dependency-injection/hilt-jetpack?hl=ko#viewmodelscoped">ViewModelScope를 설명하는 곳에 위와 같은 글</a>이 적혀있다.</p><p>즉, 단일 인스턴스를 여러 ViewModel에서 공유해야 하는 경우 @ActivityRetainedScoped 또는 @Singleton을 사용하여 범위를 지정해야 한다 라고 맨 마지막에 적혀있다.</p><p>내가 하고자 하는 것에 매우 근접했다.<br>이제 코드로 확인해보자.</p><p>위에서 본 SharedDataUseCase를 생성하는 UseCaseModule이다. <br>문서에서 찾은대로 ActivityRetainedScoped를 지정해주면 된다.</p><pre>@Module<br>@InstallIn(ActivityRetainedComponent::class)<br>object UseCaseModule {<br><br>    @Provides<br>    @ActivityRetainedScoped<br>    fun provideGetSharedDataUseCase(<br>        sharedRepository: SharedRepository<br>    ) = GetSharedDataUseCase(<br>        sharedRepository = sharedRepository<br>    )<br><br>}</pre><p>그리고 사용하는 ViewModel에서는 주입 받아서 사용하기만 하면 된다.</p><pre>@HiltViewModel<br>class HomeViewModel @Inject constructor(<br>    private val getSharedDataUseCase: GetSharedDataUseCase<br>): ViewModel() {<br><br>      //your code here...<br><br>}</pre><p>당연히 이름 그대로 알 수 있겠지만 ViewModelScoped를 사용해서 UseCase를 생성해선 안 된다.<br>그렇게 되면 유스케이스가 각각 뷰모델에 맞게 생성되게 데이터는 절대 공유될 수 없다.</p><p>해당 글을 통해 달성하고자 했던 목표는 불필요하게 적게 되는 보일러 플레이트 코드를 줄이고 좀 더 효율적으로 데이터를 관리 할 수 있는 방법을 찾는 것이었다.</p><ol><li>여러 ViewModel에서 데이터를 공유하기</li><li>ViewModel이 굳이 View를 통해서 상위/하위에 데이터를 전달하지 않기</li><li>ViewModel간 하위 레이어를 통해서 데이터를 공유하기</li><li>ViewModel간 공유하는 UseCase의 생명주기를 Activity에 맞게 매핑하기</li></ol><p>위와 같은 목표들이 있었고 단순한 아이디어부터 공식 문서를 찬찬히 읽음이 중요한 포인트까지 있다.</p><p>지금까지 내가 프로젝트에서 맞닥뜨린 요구사항을 풀어낼 수 있는 방식을 공유해보았다.</p><p>물론, 이보다 더 효율적이고 더 어울리는 방식이 있을 수 있다.<br>(이 글을 읽고 누군가 더 나은 방법을 공유해주신다면 너무 좋을 것 같다.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6d9dbf2682b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>