<?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 Tim on Medium]]></title>
        <description><![CDATA[Stories by Tim on Medium]]></description>
        <link>https://medium.com/@bso11246?source=rss-2c7333267a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7f1alpu3yjxDsm7z8Y3QcQ.jpeg</url>
            <title>Stories by Tim on Medium</title>
            <link>https://medium.com/@bso11246?source=rss-2c7333267a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:02:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bso11246/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[2024 우아콘 정리]]></title>
            <link>https://medium.com/@bso11246/2024-%EC%9A%B0%EC%95%84%EC%BD%98-%EC%A0%95%EB%A6%AC-c37feb183b0d?source=rss-2c7333267a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c37feb183b0d</guid>
            <dc:creator><![CDATA[Tim]]></dc:creator>
            <pubDate>Sat, 25 Jan 2025 05:57:52 GMT</pubDate>
            <atom:updated>2025-01-25T05:57:52.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZW388SduIu_pI47X" /><figcaption>Photo by <a href="https://unsplash.com/@headwayio?utm_source=medium&amp;utm_medium=referral">Headway</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>배달의 민족 API Gateway</h3><h3>API Gateway란?</h3><p>클라이언트의 요청을 적절한 서비스로 연결<br>인증, 보안, 모니터링, 탄력성 같은 서비스들의 공통적인 횡단 관심사를 처리한다.</p><h3>배달의민족에서 API Gateway가 필요한 이유</h3><p>모노리틱 -&gt; MSA로 전환<br>MSA에서 게이트웨이가 왜 필요한가?</p><ol><li>클라이언트 &lt;-&gt; 서비스간 의존성 증가</li><li>회원정보 API 면, 불필요한 정보가 클라이언트에 노출. (이메일만 필요한데 이름, 나이, 등등까지.)</li><li>클라이언트에 비즈니스 정책이 노출. A 서비스와 C 서비스를 직접 호출해서 그 결과를 조합하는 등의 일이 필요.</li></ol><p>서비스가 분리되었기 때문에 관리 주체가 필요했다.</p><ul><li>도메인과 클라이언트간 의존 제거</li><li>필요한 정보만 전달</li><li>비즈니스 정책이 반영된 결과를 전달</li></ul><p>-&gt; 프론트서버로 해결 (게이트웨이 아님. API Gateway 패턴)<br>프론트서버 또한 모놀리틱이니, 분리될 수 있다. 따라서 늘어날 수 밖에 없다. (그렇다고 마이크로 서비스의 숫자와 프론트서버의 숫자가 같은건 아님)</p><p>비즈니스와는 무관한 영역에서, 공통적으로 처리해야하는 문제들: 횡단관심사 문제<br>수 많은 프론트서버의 횡단관심사 문제를 공통적으로 처리해야할 필요성이 생겼다.<br>이런 횡단관심사 문제를 처리하는 무언가가 필요하다. 그게 API Gateway이다.</p><h3>API Gateway 패턴 vs API Gateway</h3><p>API Gateway 패턴은 프론트서버를 둠으로써 클라이언트와 서버간의 문제를 해결.<br>API Gateway 은 프론트서버간의 횡단관심사 문제를 해결</p><p>API Gateway는 비지니스를 처리할 수 없다. 어떤 비즈니스에도 종속적이면 안된다. 모든 서비스의 횡단관심사를 해결해야하기 때문에.</p><h3>배달의 민족의 API Gateway</h3><p>API Gateway는 분산되어야하고, 스케일러블 하다. 단일 실패지점이 되면 안되기 때문에.<br>스프링 클라우드 게이트웨이를 커스텀함. (필터 체인을 커스텀함)<br>라우팅은 호스트기반.<br>요청단위에는 필터를 설정.</p><p>기능:</p><ol><li>인증: MSA환경에서 세션 기반 인증에서는 특정 서버에 연결되어 세션 정보를 확인해야 하므로, 서버 간의 의존성이 생김. JWT는 서버가 여러 인스턴스일지라도 각 인스턴스에서 JWT를 독립적으로 검증할 수 있습니다. 이로 인해 특정 서버가 장애가 발생해도 다른 서버에서 요청을 처리할 수 있습니다. 따라서 JWT 도입. 하지만 JWT는 각 서비스에 전달되는데 시간이 오래걸림. 같은 이유로 key 유출등에 빠르게 대응하지 못함. JWT 만 쓴다면 JWT 인증 프로세스가 실패했을 경우 전체 인증이 실패하게됨. 따라서 스프링 클라우드 필터를 통한 인증 또한 도입하게 됨.. JWT 랑 같이 써서 단일 실패지점 문제를 해결.</li><li>라우팅: 사내 임직원은 테스트서버로 보낸다든가 가능.</li><li>보안: 각 서비스에서 하지않고, API 게이트웨이에서 한다.</li><li>흐름제어: 리퀘스트를 통제. retry, static response fallback</li></ol><h3>XML을 Compose로 전환하기</h3><p>Compose 이점</p><ul><li>코틀린으로 UI 작성가능 (생산성 확대)</li><li>선언적 UI로 가독성 높임</li><li>유연성. XML 과 호환가능.</li><li>프리뷰 제공. (애니메이션, 인터렉션 가능)</li></ul><p>Compose 전환의 필요성</p><ul><li>효율적인 ui 개발과 생산성을 위해</li><li>공통된 디자인 시스템 도입</li><li>재사용 및 모듈화</li></ul><p>전환시 고려해야할 것들</p><ul><li>완전전환 vs 점진적 전환</li><li>기존 뷰 시스템과의 상호 운용성 (기존 기능에 영향이 없어야)</li></ul><p>사례</p><ol><li>Row Vertical이 안맞을때: 숫자는 괜찮은데 숫자+한글일 경우 정렬이 틀어짐. AlignmentLine, BaseLine 을 이용해서 정렬하기 때문. BaseLine 은 AlignmentLine 의 하위요소. -&gt; alignByBaseline 으로 정렬해서 해결.</li><li>Text의 drawableEnd : inlineContent 활용.</li><li>퀵메뉴: LazyHorizontalGrid의 높이는 고정되어야하는데, 컨텐츠의 높이로 하고 싶다. 이를 위해 subcomposeLayout를 사용. : 여러 단계의 measure, 지연된 place. subcompose를 통해 컴포지션한 컴포저블을 placeable로 얻을 수 있고, constraint를 얻을 수 있다. 이후 특정 시점에 place 할 수 있다.</li><li>LazyRow, 가장 높은 아이템의 높이로 고정시켜주세요라는 요구사항. LazyRow는 실제 아이템이 그려지기까지는 아이템의 높이를 알 수 없다. 이를 위해서 가장 높을 걸로 예상되는 아이템의 높이를 구해야함. 이를 위해 subcomposeLayout를 사용. item을 순회하면서 subcompose를 해서 가장 높은 placeable을 구함. 그렇게 가장 높은 아이템의 높이를 구할 수 있음.</li><li>AutoSize Text: 공간은 한정되어 있는데, 글자가 많아지면 글자 크기가 줄어드는것. 그리기 전에 폰트가 영역을 넘는지 확인하기 위해 draw가 지연되어야함. drawWithContent 이용. 텍스트가 영역을 넘는지는 onTextLayout의 textLayoutResult의 didOverflowWidth로 확인. 혹은 TextMeasurer를 이용. onTextLayout은 내부적으로 그리기 때문에 성능상 좋지 않음 TextMeasurer를 추천.</li></ol><p>장점</p><ul><li>공통 디자인 시스템 사용 가능</li><li>UI로직이 필요한 경우 코틀린으로 작성가능</li><li>XML 코드 관리 필요없어짐 (코드 간소화)</li><li>RecyclerView Adapter viewholder등 필요 없어짐</li></ul><p>단점</p><ul><li>리컴포지션에 대한 고민</li><li>러닝커브</li><li>기존 프로젝트와의 호환성 (view 시스템?)</li><li>아직 없는 기능이 많음.</li></ul><h3>통합테스트로 보다 안전한 웹프런트엔드 서비스 개발하기</h3><p>단위 테스트</p><ul><li>검증 가능한 영역이 제한적</li></ul><p>통합테스트</p><ul><li>여기서 말하는 통합테스트는, 프론트엔드 코드에서 하는 통합테스트.</li><li>모듈간의 상호작용 검증</li><li>서버 응답에 따른 동작 확인</li><li>실제 시나리오와 유사하지만 테스트의 설정과 유지가 어려움</li></ul><p>E2E테스트</p><ul><li>사용자가 어플리케이션을 사용하는 환경을 재현해서 전체 시나리오 검증</li><li>느린 속도.</li></ul><p>예전 배민의 프론트엔드 테스트</p><ul><li>주로 단위테스트</li><li>논리적 오류 검증</li><li>내부 상태 업데이트 검증</li><li>이벤트 핸들러 호출 검증</li></ul><p>그러나, 실제 앱은 테스트하는 대상과 멀리 떨어져있음. 저수준의 단위테스트 만으로는 어플리케이션의 동작을 충분히 보장할 수 없다.</p><p>단위테스트의 허점</p><ul><li>모듈의 연동과정에서 문제가 발생할 수 있다.</li><li>서버상태, 전역 상태 변화를 동반하는 시나리오 검증을 못함</li><li>코드 수정에 따른 영향 범위를 충분히 파악하기 어렵다. (코드 수정은 연결된 모든 모듈에 영향이 가므로)</li></ul><p>그래서 통합테스트를 작성하자는 결론이 났다.</p><p>통합테스트 이점</p><ol><li>모듈 연동과정에서의 결함 발견 : 이벤트 리스너를 반대로 설정했던 경우 (수정과 삭제). 이벤트 리스너 자체는 잘 호출되기 때문에 단위테스트는 통과하지만, 통합테스트는 통과하지 못한다.</li><li>API 모킹을 통해 모듈간의 상호작용 테스팅 가능</li><li>변경된 부분의 영향범위 테스트 가능. (A를 고쳤을때 B에서의 이슈를 잡아낼 수 있음. 정책의 충돌이라든가.)</li></ol><p>장점</p><ul><li>코드 수정에 대한 자신감, 신뢰감</li><li>빠른 피드백</li><li>코드 품질 향상</li></ul><p>단점</p><ul><li>고수준의 테스트일수록 높아지는 의존성과 복잡성.</li><li>유지보수의 어려움.</li><li>테스트 실패시 어떤 지점에서 실패했는지 알기 어려움</li></ul><p>단위테스트, 통합테스트 둘다 필요.<br>해당 기능이 어떤 테스트를 필요로 하는지에 대한 감이 필요</p><h3>Q&amp;A</h3><p>Q: 테스트 자체에 버그가 있어서 버그를 못잡은 경험?<br>A: 테스트는 서로 독립적이여야하지만, 통합테스트는 독립성을 지키지 못할 때가 많다.<br>독립성을 지키도록 주의해야한다. 독립성이 없는데, 테스트가 통과되면 그건 신뢰할 수 없는 테스트이기 때문이다.</p><p>통합테스트 같은 고수준의 테스트는 CI가 실패할 때가 많다.<br>CI 인스턴스의 리소스 때문에 실패하는 경우가 많다.<br>인스턴스의 리소스를 늘리거나, 테스트를 독립적으로 실행하는게 팁이다.</p><p>자주 변하지 않고, 중요한 동선 위주로 통합테스트를 작성하는게 좋다.</p><h3>디자인시스템 문서를 생동감 있게 만들기 위한 ‘우아한플레이그라운드’ 제작기</h3><p>Figma Code Connect 비슷한것.</p><h3>우아한 플레이그라운드가 필요했던 배경</h3><ul><li>공통 컴포넌트를 어떻게 쓰는지 학습하기 위해서 문서 사이트를 갔지만, 개요 정도밖에 없었다.</li><li>스토리북에서는 노출되지 않는 코드(변수, 함수)등이 있어서 학습하기 어려웠다.</li><li>실제 코드베이스로 학습하는 수밖에.</li><li>테스트하려면 빈 프로젝트를 만들어 해봐야함.</li><li>공통 컴포넌트의 복잡한 모양과, 코드가 잘 일치되지 않음. (시안을 보고 어떻게 공통컴퍼넌트를 활용할지 알기 어려움)</li><li>더 많은 예제, 더 많은 렌더결과물, 실시간 편집/렌더를 지원하는 예제가 필요하다</li></ul><h3>구현</h3><ul><li>에디터와 프리뷰: 에디터는 monaco-editor, 프리뷰는 iframe을 사용한다.</li><li>npm 라이브러리 로드: ESM 기반인 CDN인 esm.sh 에서 npm 라이브러리 로드. cdn 주소를 importmap 을 사용해서 라이브러리 명으로 매핑함.</li><li>TypeScript, JSX 지원하기: iframe에서 돌아가야하기 때문에 자바스크립트로 변환해야함. esbuild-wasm을 사용. (다양한 트랜스파일 도구가 있지만 브라우저 런타임에서 실행가능하고, 번들링이 가능하기 때문.)</li><li>TypeScript IntelliSense (정적분석) 지원하기: monaco-editor의 타입스크립트의 랭귀지 서버는 리액트의 패키지를 모르기 때문에 에러가 뜸. 브라우저 런타임에서는 파일시스템이 존재하지 않는다. 타입 스크립트 랭귀지 서버에서 파일을 읽는 함수를 수정해서 메모리에 있는 타입정보를 반환하도록 수정하면 됨. 타입정의는 esm.sh 에서 받으면 됨.</li><li>반복되는 코드 구문을 생략하기 위해 인-메모리 파일 시스템을 구축해 사용. 하지만 브라우저에서는 인 메모리 파일경로를 참조하는데 오류가 생길 것임. esbuild 의 번들링과정의 load 단계를 커스텀하면 됨. esbuild 플러그인을 만들어서 커스텀할 수 있음.</li></ul><p>유지보수를 위해 연관도를 기준으로 기능 응집. 응집된 기능들을 각각의 모듈로 만듦.<br>-&gt; 에디터, 프리뷰, 타입, 번들러 등등의 모듈로..</p><p>입력한 코드를 공유하고 싶다.<br>-&gt; 코드를 lz-string으로 압축후 base64로 인코딩해서 url에 파라미터로 넣어서 공유할 수 있게 함.</p><h3>네이티브 모듈? 그게 뭔데요? React-Native로 만드는 배민 커넥트 앱 두 번째 이야기</h3><p>리액트 네이티브 만으로는 네이티브 기능을 사용할 수 없는 것이 많다.<br>그럴때는 네이티브 모듈, 네이티브 컴포넌트를 사용하면 된다.</p><p>리액트 네이티브용 네이티브 모듈 라이브러리가 여러가지 있지만,<br>네이티브 모듈을 만들었던 이유</p><ol><li>방법이 없을때 (ex. 지도 컴포넌트)</li><li>문제가 있을때 (쓰기에 너무 크거나, 위험요소가 있는 라이브러리인 경우)</li></ol><h3>지도 컴포넌트 이야기</h3><p>리액트 네이티브의 생명주기와 Android의 생명주기가 다른 경우가 생긴다<br>-&gt; 리액트 네이티브에서 직접 Android 생명주기 메서드를 호출하는 등으로 해결</p><h3>안드로이드 알림채널 이야기</h3><p>기존 리액트 네이티브 라이브러리는 너무 많은 필요없는 기능을 가지고있어, 그냥 내재화 하자.<br>네이티브 모듈을 만들기로 함.<br>안드로이드 리소스 id(16진수)를 통해 소리를 지정하는 경우, 간헐적으로 소리가 나지 않는 이슈가 있었다.<br>안드로이드의 리소스 id는 자동생성되고 상황에 따라 바뀌기 때문에 리소스 Id자체가 아니라, 파일 이름을 지정해주었어야 했다.</p><h3>우아한 데이트 허브. 일 200억 건 데이터 안전하게 처리하는 대용량 시스템 구축하기</h3><h3>시스템 아키텍쳐</h3><p>WOOWA HUB 아키텍쳐<br>WOOWA HUB는 여러 데이터의 소스를 묶는 허브다.<br>분당 700만 요청, 하루 약 200억 데이터</p><ol><li>데이터 통합</li><li>데이터 처리</li><li>데이터 저장</li><li>데이터 조회</li></ol><p>WOOWA HUB 는<br>Event Driven architecture 로 되어있다.</p><h3>STEP1. 데이터통합</h3><p>카프카로 바로 이벤트를 발행하지 않고, 퍼블리셔 서버를 거친다. 카프카에서 바로 서비스로 메시지가 전달되지않고 리스너서버를 거친다<br><strong>Back Pressure 처리 가 중요하다.</strong></p><p>퍼블리셔 서버의 이점</p><ol><li>기술 추상화. (이벤트 브로커 교체 가능. 이벤트 기반 대신 다른 기반의 아키텍쳐 선택 가능.)</li><li>메시지 형상 관리. (메시지 구조를 인터페이스, IDL 로 제한)</li><li>메시지 순서 관리 가능 (?)</li></ol><p>리스너 서버의 이점</p><ol><li>메시지별로 컨수머가 처리할 스레드 개수 지정가능. 이 덕에 <strong>Back Pressure 처리</strong>가 가능</li><li>메시지 재발행 가능</li><li>컨슘 시작, 중지를 제어할 수 있다.</li></ol><h3>STEP2. 데이터 처리</h3><p>비지니스 요구사항에 따라서 데이터 처리 방법이 달라진다. (가게 정보, 주소지 등등의 요건..)<br>안전하고, 유연하고, 빠르게 처리할 수 있어야한다.</p><ol><li>트랜잭션 단위를 유연하게 구성하는 것이 어려움</li><li>특정 동작만 별도로 수행하기 어려움 (프로세스의 많은 단계에서, 외부시스템 오류일시 프로세스를 처음부터 재시작 해야하는 경우가 있음)</li></ol><p>데이터를 기준으로 생각하자.<br>우아한 워크플로우</p><p>Task는 독자적인 처리가 가능한 단위의 비즈니스 로직<br>독자적으로 수행가능한 마이크로 트랜잭션</p><p>데이터가 들어왔을때</p><ol><li>원본 저장 (Main Task)</li><li>부가적으로 수행되어야하는 작업 (SubTask)</li></ol><p>Main Task -&gt; SubTaskA -&gt; SubTaskB 처럼 이어 붙일 수 있음.<br>Main Task -&gt; SubTaskC -&gt; SubTaskA 처럼 분기가 일어날 수도 있음.</p><p>SubTask는 서로 영향을 미치지 않는다 (실패가 전파되지 않는다)<br>하나의 Task는 트랜잭션.</p><h3>STEP3. 데이터 저장</h3><p><strong>높은 쓰기와 읽기 성능을 확보해야한다.</strong></p><ul><li>고가용성 (마스터 서버 레플리카로 클러스터링 구현)</li><li>분산처리를 통해 부하분산.</li><li>테이블 INDEX가 커지면 DML 성능 저하. 따라서 수평 파티셔닝 수행.</li><li>파티션이 많아지면 여러 이슈가 발생하기 때문에 샤딩을 수행.</li></ul><p>파티셔너 &amp; 샤딩 관련 고민:</p><ol><li>어디서 구현해야하나. : 어플리케이션 레벨에서.</li><li>어떻게 수행할 것인가 : key기반 + 디렉터리 기반 샤딩.</li></ol><p>key기반<br>해시함수를 통해 파티션 번호를 얻음.</p><p>디렉터리 기반<br>파티션별 어떤 db가 매핑되는지 Lookup 테이블을 조회</p><p>그냥 key기반만 쓸 수도 있었지만<br>핫파티션, 콜드파티션에 대한 고민 때문에 이러한 구조를 채택 (데이터가 굉장히 많기 때문에 어떻게 균등하게 나눌 것인가 고민.)</p><p>핫파티션은 따로, 콜드파티션은 같이 두도록 함. (핫 파티션이 발생하면 그대로 복제 후, 기존 요청들을 복제본에 옮기고, 복제 파티션에 있는 콜드파티션은 기존 파티션으로 옮기고 기존 파티션의 핫파티션을 제거)</p><p>어플리케이션 레벨에서 필요했기 때문에 모듈로 만듦.</p><p>1억건이 한번에 오면 결국 터지지 않냐?<br>-&gt; 카프카 배압 조절 (?) 로 CPU 사용량이 팍 튀지 않도록 함</p><h3>네트워크</h3><p><strong>각 서버 상황에 맞춰서 다양한 서버 스택을 선택 할 수 있어야 한다.</strong><br>RPC 로 이루어져있기 때문에 IDL 로 형상관리 가능.<br>GSON 직렬화 시간이 오래걸리는거 아니냐? -&gt; GSON 말고도 여러 실험을 통했지만 상황에 따라 뭐가 더 나은가는 달랐음. 따라서 여러 포맷을 사용할 수 있어야함.<br>이를 위해선 두 노드간 약속이 선행되어야 한다. JSON 으로 할지. gzip으로 합축해서 보낼지. 이를 파라미터로 보낼 수 있어야한다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c37feb183b0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nested Scroll Problems in Android]]></title>
            <link>https://medium.com/@bso11246/nested-scroll-problems-in-android-79a2e80ead88?source=rss-2c7333267a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/79a2e80ead88</guid>
            <dc:creator><![CDATA[Tim]]></dc:creator>
            <pubDate>Sun, 12 May 2024 09:07:33 GMT</pubDate>
            <atom:updated>2024-05-26T10:29:25.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X0f83OOzgFk9DqTz" /><figcaption>Photo by <a href="https://unsplash.com/@taypaigey?utm_source=medium&amp;utm_medium=referral">Taylor Flowe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In Android development, sometimes nested scroll events behave in unexpected ways.</p><h4>ViewPager2 In CoordinateLayout</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*B3SM-2ZFaRnywnJBQot7vw.png" /><figcaption>Feed Screen</figcaption></figure><p>CoordinatorLayout can cause the CollapsingToolbarLayout to collapse when the user scrolls down on ViewPager2. However, when attempting to scroll down ViewPager2 while dragging RecyclerView in Section 1, the CollapsingToolbarLayout does not collapse; instead, only ViewPager2 is scrolled down.</p><p>This occurs because the RecyclerView inside Section1 is initiating the nested scroll. To collapse the CollapsingToolbarLayout, the vertical scroll of ViewPager2 should be delivered to the CollapsingToolbarLayout, but the nested scroll of RecyclerView on Section1 prevent it. Therefore, setting nestedScrollEnabled to false resolves the problem.</p><pre>binding.rv.isNestedScrollingEnabled = false</pre><p>But what if the nested view scrolling is not a RecyclerView but another ViewPager? In this case, we need to locate the RecyclerView within the ViewPager2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f06ab99ea46335bc30d894f07de61aae/href">https://medium.com/media/f06ab99ea46335bc30d894f07de61aae/href</a></iframe><p>we can resolve this issue by setting isNestedScrollingEnabled to false to it too.</p><p>This method can be unreliable for obtaining a RecyclerView from ViewPager2 because it relies on the getChildAt(position) function and Reflection. Someday in the future, the RecyclerView in ViewPager2 might not be the first child of ViewPager2 or might not be assigned as a ‘mRecyclerView’ variable.</p><h4>RecyclerView In ViewPager2</h4><p>When the user tries to horizontally scroll Section 1’s RecyclerView, the ViewPager2 swipes to the next page, which is not the desired behavior. To make the RecyclerView scrollable, we can use the ViewParent.requestDisallowInterceptTouchEvent function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0LZT_W2S7tqt4pod.png" /></figure><p>In Android, the touch event is notified downwards and handled upwards. If we use requestDisallowInterceptTouchEvent on ViewGroupB, ViewGroupB cannot intercept touch events, so that the view at the bottom can still handle touch events. Therefore, in this case, we need to call requestDisallowInterceptTouchEvent on ViewPager2 so that the RecyclerView in Section1 can handle it. This can be implemented using a custom view named <a href="https://github.com/android/views-widgets-samples/blob/master/ViewPager2/app/src/main/java/androidx/viewpager2/integration/testapp/NestedScrollableHost.kt">NestedScrollableHost</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0fc3b2280c6cbea35d5b7b17d4940d7/href">https://medium.com/media/e0fc3b2280c6cbea35d5b7b17d4940d7/href</a></iframe><p>This solution is suggested by Google to solve the problem and is mentioned in the <a href="https://developer.android.com/develop/ui/views/animations/vp2-migration?hl=ko#nested-scrollables">Android official documentation.</a></p><p>NestedScrollableHost allows the parent to intercept touch events when the direct child of NestedScrollableHost can no longer be scrolled. If you want to change this behavior, you can modify the canChildScroll method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2fac354aedfed6a5a1e4afedf30765b/href">https://medium.com/media/a2fac354aedfed6a5a1e4afedf30765b/href</a></iframe><p>This new NestedScrollableHost prevents the parent ViewPager from being swiped even if the child scrollable view (RecyclerView or ViewPager2) is no longer scrollable. This can be useful when you want to prevent users from mistakenly swiping the page instead of scrolling through the content within the page in this way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79a2e80ead88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Synchronization Among Screens]]></title>
            <link>https://medium.com/@bso11246/state-syncronization-among-screens-a1047ad13782?source=rss-2c7333267a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1047ad13782</guid>
            <dc:creator><![CDATA[Tim]]></dc:creator>
            <pubDate>Tue, 07 May 2024 13:42:38 GMT</pubDate>
            <atom:updated>2025-01-27T10:58:15.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Py-9yFCKxnsackqK" /><figcaption>Photo by <a href="https://unsplash.com/@obionyeador?utm_source=medium&amp;utm_medium=referral">Obi - @pixel8propix</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When developing an Android app, especially a social networking app (SNS), we often encounter the common issue of synchronizing state among screens.</p><p>For example, on post detail page, users can view other users’ posts and interact with them (e.g., like, save, comment). Subsequently, when navigating back to post list page, those changes made by the user need to be reflected.</p><p>This can be implemented in various ways.</p><p><strong>Global Event</strong></p><p>For instance, when a user saves a post, the producer dispatches an event via EventDispatcher, which the subscriber receives and handles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e65ef055dfbaff95cd910f3accb3064/href">https://medium.com/media/8e65ef055dfbaff95cd910f3accb3064/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef6e3c1f4e9a96d6750102138cfaa84d/href">https://medium.com/media/ef6e3c1f4e9a96d6750102138cfaa84d/href</a></iframe><p>This is a simple solution and works fine. However, overuse of global events can make the code hard to read and prone to errors. There’s a risk of forgetting to handle some events. Furthermore, if an event is missed for any reason, the state among screens can become inconsistent.</p><p>With Paging3, it becomes more complex. PagingData is merely a flow of data and cannot be modified. When the subscriber receives a global event, it may need to change the local data to handle it. However, if the local data is PagingData, it cannot be directly modified.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1280e212cde28c1a9c5ec6a433bc2c2/href">https://medium.com/media/c1280e212cde28c1a9c5ec6a433bc2c2/href</a></iframe><p>One approach is to change the adapter’s snapshot and submit it to the adapter again, but this violates the ‘single-source-of-truth’ rule. In this case, the local data could be a viewModel and the adapter’s snapshot.</p><p><strong>Global State</strong></p><p>Global state can be implemented in various ways, but one recommended approach is to use Stateflow on the Repository.</p><blockquote>Ideally, using a local database over a memory cache consumes less memory and can make the app offline-first. However, the more complex the entity you have to cache, the harder it is to implement. Therefore, I personally recommend using a memory cache in such cases.</blockquote><p>For example, the PostRepository, which can change post state through actions like liking, saving, or deleting a post, can have a Post Cache. The Post Cache is a map of post IDs and their states.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5b093e595c5fbc3261eda7b9f88df51/href">https://medium.com/media/c5b093e595c5fbc3261eda7b9f88df51/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d26d92bbfae22c5c1a2aa070e2a7c42a/href">https://medium.com/media/d26d92bbfae22c5c1a2aa070e2a7c42a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed044db46dcb13d2853dc3eebf8212ec/href">https://medium.com/media/ed044db46dcb13d2853dc3eebf8212ec/href</a></iframe><p>If the post’s like state changes, the likeCache is updated, and downstream flow is executed to reflect these changes. These caches may be cleaned up when fetching fresh data from the Remote Server, which can be done with a simple postCache.clear() function.</p><p>This approach provided several advantages:</p><ul><li>Screens could subscribe to the state and intuitively use the latest data.</li><li>We minimized side effects, implementing a clearer and more stable structure compared to the event-based approach.</li><li>Using memory instead of a local database allowed us to manage complex nested data more simply.</li></ul><p>With this method, we significantly reduced the likelihood of bugs and greatly improved the user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1047ad13782" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nested RecyclerView optimization]]></title>
            <link>https://medium.com/@bso11246/nested-recyclerview-optimization-6a739eefaec4?source=rss-2c7333267a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a739eefaec4</guid>
            <dc:creator><![CDATA[Tim]]></dc:creator>
            <pubDate>Sun, 05 May 2024 08:43:39 GMT</pubDate>
            <atom:updated>2024-05-05T08:46:37.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9QkSASsliVG_7lUK" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">rivage</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>RecyclerView is a commonly used Android component to implement a list of items. However, to ensure optimal performance, certain practices must be followed. If not, RecyclerView can cause your app to slow down.</p><p>To understand this post, you should have some basic knowledge of RecyclerView. I recommend reading this <a href="https://medium.com/android-news/android-dev-tip-4-91b7757b1f0a">article</a> for background information.</p><blockquote>The whole thing becomes substantially less intuitive when you you want the RecyclerView to wrap its contents. In that case the size of the RecyclerView becomes the size of all item Views. As a result, RecyclerView itself is not scrollable anymore and no items can be scrolled off from the RecyclerView’s visible area. RecyclerView sees its whole area as a <em>visible area</em>.</blockquote><p>With this in mind, let’s look at the following UI scenario:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*zmi3eWClS4mDaBfGF9tXig.png" /></figure><p>In this screen, there are multiple sections arranged vertically, with each section paginated. To display these sections, we need a vertical RecyclerView for sections, with each sections also containing horizontal RecyclerViews.</p><p>In this configuration, there are no performance issues, even with nested RecyclerViews, because the orientations are different between the outer and inner RecyclerViews.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*1ZZpbirC_cVtAvTESdAiIw.png" /></figure><p>However, when the outer RecyclerView and the inner RecyclerView within a section have the same orientation, issues can occur. Specifically, if Section 2 has paginated items, all items in Section 2 will be drawn at once, causing RecyclerView’s ViewHolders not to be recycled. This can lead to critical performance issues.</p><p>There are two approaches to solve this problem:</p><p><strong>Approach 1: Use a single RecyclerView with a GridLayoutManager.</strong></p><ul><li>This requires creating three types of ViewHolders:</li></ul><ol><li>ViewHolder for the section title.</li><li>ViewHolder for the RecyclerView in Section 1.</li><li>ViewHolder for the items in Section 2.</li></ol><p>In this approach, you can set the span sizes using spanSizeLookup. The section title and RecyclerView in Section 1 can occupy 3 spans, while each item in Section 2 occupies 1 span.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b896cea14a95c7d411308d57a6329ef/href">https://medium.com/media/8b896cea14a95c7d411308d57a6329ef/href</a></iframe><p>Additionally, to create padding between items, you can use ItemDecoration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*GGehUIFdcjMEsa2KIkFBWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*tjh8DHdWVMuDxi56l9STBg.png" /></figure><p>When we set padding for the first and last columns of items, the result is that the items in the center do not shrink as expected. Ideally, we should ensure that all items in Section 2 are the same size, but this doesn’t always work out as planned.</p><p>To achieve this, we need to find a way to properly place each item in the grid while maintaining consistent padding. However, I haven’t yet found an effective solution to achieve this.</p><p><strong>Approach 2: Use separate horizontal RecyclerViews for each row of Section 2.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*AMs2IFeck5_CRcf30xqRtQ.png" /></figure><p>In this case, to recycle ViewHolders, we need to use RecyclerViewPool. The RecycledViewPool lets you share Views between multiple RecyclerViews, improving performance by reusing existing views rather than creating new ones each time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4db72134b4707347b6ac4065951d225f/href">https://medium.com/media/4db72134b4707347b6ac4065951d225f/href</a></iframe><p>We need to set maxRecycledViews for each viewType explicitly because the default size is 5. Without this setting, only 5 ViewHolders for each viewType will be recycled. I chose to set this to 30 because the maximum visible item count is about 15-20. Keeping in mind that RecyclerView creates extra items in off-screen areas for optimization, I added an additional 15.</p><p>However, this approach has a drawback: when an item is removed or added, the RecyclerViews for the affected position and below are redrawn. If you have just one RecyclerView for all items, DiffUtil can optimize item changes, but in this case, it might not work as expected.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a739eefaec4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Development Issue: App Crash Caused by View.post()]]></title>
            <link>https://medium.com/@bso11246/android-development-issue-app-crash-caused-by-view-post-6cf1e65b2762?source=rss-2c7333267a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cf1e65b2762</guid>
            <dc:creator><![CDATA[Tim]]></dc:creator>
            <pubDate>Sun, 05 May 2024 01:09:16 GMT</pubDate>
            <atom:updated>2024-05-05T01:12:34.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tYEIjvbkOny_d8GN" /><figcaption>Photo by <a href="https://unsplash.com/@bundo?utm_source=medium&amp;utm_medium=referral">Bundo Kim</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In Android development, when attempting to retrieve UI data from a view, we occasionally use the View.post() function. However, this approach can lead to app crashes.</p><p>Consider a scenario where a fragment is opened using replace() and subsequently opened again rapidly, such as due to a deeplink, replacing the fragment twice in quick succession. If View.post() is employed within this fragment, it can result in an app crash.</p><p>This is because the fragment is destroyed by replace(), but the code delayed by View.post() continues to execute, referencing variables associated with the destroyed fragment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b56671e899231c6fdaba797d45610361/href">https://medium.com/media/b56671e899231c6fdaba797d45610361/href</a></iframe><p>To mitigate this issue and prevent app crashes, one approach is to verify whether the fragment is added to its activity using Fragment.isAdded().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd2a742edf155f879123c8e0971611be/href">https://medium.com/media/dd2a742edf155f879123c8e0971611be/href</a></iframe><p>To simplify this process, an extension function can be utilized.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bae21330b09258d6765f685bb274f771/href">https://medium.com/media/bae21330b09258d6765f685bb274f771/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cf1e65b2762" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stateflow를 RecyclerView Item에서 쓰면 안되는 이유]]></title>
            <link>https://medium.com/@bso11246/stateflow%EB%A5%BC-recyclerview-item%EC%97%90%EC%84%9C-%EC%93%B0%EB%A9%B4-%EC%95%88%EB%90%98%EB%8A%94-%EC%9D%B4%EC%9C%A0-e93e0dee9698?source=rss-2c7333267a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e93e0dee9698</guid>
            <dc:creator><![CDATA[Tim]]></dc:creator>
            <pubDate>Tue, 30 May 2023 11:32:48 GMT</pubDate>
            <atom:updated>2023-05-30T11:32:48.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WWO_STXVgTVDPvmW" /><figcaption>Photo by <a href="https://unsplash.com/@thefredyjacob?utm_source=medium&amp;utm_medium=referral">Fredy Jacob</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>RecyclerView Item을 업데이트 할때 Stateflow와 Databinding을 사용하는 경우가 있다. Adapter에 넘겨주는 데이터 클래스에 Stateflow를 멤버변수로 선언해 그에 따라 UI를 업데이트 하면 notifyDataSetChanged 류의 메소드를 호출하지 않고도 UI를 업데이트 할 수 있다. 특히나 Paging3 라이브러리를 사용하는 경우 PagingData는 일부를 변경할 수가 없기 때문에 이런 식으로 종종 구현하고는 한다.</p><p>이런 방식은 편리하지만 DiffUtil과 같이 사용하는 경우 문제가 있다. 리스트를 리프레쉬할때 리프레쉬 하기 전의 데이터가 메모리에서 내려가지 않고 남는다는 점이다.</p><p>리프레쉬를 하면 새로운 데이터를 submitData를 통해 어댑터에 셋팅하게 되는데, 이때 DiffUtil로 변경사항을 판단하게 된다. 만약 새로운 데이터가 이전 데이터와 동일하다고 판단되어 Adapter의 onBindViewHolder() 호출이 스킵되는 경우 View는 여전히 이전 데이터의 Stateflow를 구독하고 있게된다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*XDACg5jMys2qmMYEcqd1qw.png" /></figure><p>그러면 Adapter의 데이터는 새로운 데이터로 변경이 되었지만 View에 바인딩된 데이터는 이전 데이터이고, View가 Stateflow를 참조하고 있으므로 이전 데이터는 메모리에서 해제되지 못한다.</p><p>그게 첫번째 문제이다.</p><p>두번째 문제는, 이 상태로 버튼을 누르거나 하는 경우 View에 바인딩된 Stateflow를 통해 UI가 업데이트 되기는 하나, 그 Stateflow는 Adpater가 현재 가지고 있는 Stateflow와 다른 객체이다. 따라서 스크롤 조작 등으로 onBindViewHolder가 다시 불렸을때 Adapter가 가지고 있는 Stateflow로 다시 바인딩이 되면서 이전 상태를 잃어버리게 된다.</p><p>이런 문제들 때문에 Adapter에 넘겨주는 Data에는 Stateflow를 사용해서는 안된다. 대신, Activity 나 Fragment의 ViewModel에 상태를 두고 그곳에서만 상태 업데이트를 수행하는게 바람직하다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e93e0dee9698" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RecyclerView.Adapter &ViewHolder는 이제 그만 (1) : 데이터 보여주기]]></title>
            <link>https://medium.com/@bso11246/recyclerview-adapter-viewholder%EB%8A%94-%EC%9D%B4%EC%A0%9C-%EA%B7%B8%EB%A7%8C-1-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EB%B3%B4%EC%97%AC%EC%A3%BC%EA%B8%B0-7a9ef21031f3?source=rss-2c7333267a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a9ef21031f3</guid>
            <dc:creator><![CDATA[Tim]]></dc:creator>
            <pubDate>Sun, 28 May 2023 09:02:02 GMT</pubDate>
            <atom:updated>2024-05-07T15:36:30.715Z</atom:updated>
            <content:encoded><![CDATA[<h3>RecyclerView 사용을 간편하게: Adapter, ViewHolder 일반화</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*25CYqZmxodHiiIB1dawkPw.jpeg" /><figcaption><a href="https://unsplash.com/photos/g6Wd6MS8lms">unsplash@g6Wd6MS8lms</a></figcaption></figure><p>XML기반의 프로젝트에는 RecyclerView.Adapter와 ViewHolder가 굉장히 많다. 특히나 리사이클러뷰 안에 리사이클러뷰가 있는 중첩 구조에서는 코드가 난잡해지기 쉬웠다.</p><p>이것을 간단하게 할 방법이 없을까 생각하다가 알게된 것이 Antonio라는 라이브러리였다. NaverZ에서 만든 라이브러리인데, 복잡한 레이아웃 구현을 위해RecyclerView.Adapter 와 ViewHolder를 일반화한 라이브러리이다.</p><p>Antonio 라이브러리를 사용하는 것도 좋았지만, RecyclerView와 Adapter 라는 fundamental 한 부분을 외부 라이브러리로 교체한다는 것이 꺼림직했고, NaverZ의 제페토가 컴포즈로 마이그레이션 한 시점에서 이 라이브러리의 유지보수가 잘 되고 있는지 의심스럽기도 했다.</p><p>그래서 나는 좀 더 간단한 버전을 만들어보기로했다.</p><pre>interface BindableUIModel {<br>    val bindingVariableId: Int<br><br>    @get:LayoutRes<br>    val layoutId: Int<br><br>    fun areItemsTheSame(other: BindableUIModel): Boolean<br>    fun areContentsTheSame(other: BindableUIModel): Boolean<br><br>    fun getChangePayload(other: BindableUIModel): Any? {<br>        return null<br>    }<br>}</pre><p>우선 어댑터에 사용할 데이터 모델을 정의한다.</p><ul><li>bindingVariableId : 데이터바인딩에서 사용할 데이터의 id 이다. BR 클래스로 접근 가능하다.</li><li>layoutId : 이 데이터모델이 바인딩될 레이아웃의 id 이다.</li><li>areItemsTheSame, areContentsTheSame, getChangePayload : DiffUtil.ItemCallback을 구현하기 위한 함수다.</li></ul><p>이제 실제 데이터 모델을 만들어보자.</p><pre>sealed class Section : BindableUIModel {<br>    abstract val id: Int<br>    abstract val title: String<br><br>    data class Horizontal(<br>        override val id: Int,<br>        override val title: String<br>    ) : Section() {<br>        override val bindingVariableId: Int = BR.item<br>        override val layoutId: Int = R.layout.item_section_horizontal<br>        override fun areItemsTheSame(other: BindableUIModel): Boolean {<br>            return other is Horizontal &amp;&amp; id == other.id<br>        }<br><br>        override fun areContentsTheSame(other: BindableUIModel): Boolean {<br>            return this == other<br>        }<br>    }<br><br>    data class Vertical(<br>        override val id: Int,<br>        override val title: String<br>    ) : Section() {<br>        override val bindingVariableId: Int = BR.item<br>        override val layoutId: Int = R.layout.item_section_vertical<br>        override fun areItemsTheSame(other: BindableUIModel): Boolean {<br>            return other is Horizontal &amp;&amp; id == other.id<br>        }<br><br>        override fun areContentsTheSame(other: BindableUIModel): Boolean {<br>            return this == other<br>        }<br>    }<br><br>    data class Grid(<br>        override val id: Int,<br>        override val title: String<br>    ) : Section() {<br>        override val bindingVariableId: Int = BR.item<br>        override val layoutId: Int = R.layout.item_section_grid<br>        override fun areItemsTheSame(other: BindableUIModel): Boolean {<br>            return other is Horizontal &amp;&amp; id == other.id<br>        }<br><br>        override fun areContentsTheSame(other: BindableUIModel): Boolean {<br>            return this == other<br>        }<br>    }<br>}</pre><p>리사이클러뷰에 여러개의 섹션이 있다고 가정하고 sealed class를 이용해 각각의 섹션 데이터를 표현해보았다.</p><p>이런식으로 표현하면 좋은 점은 해당 데이터가 어떤 UI를 표현하는지 직관적으로 알 수 있다는 것이다.</p><p>다음은 이 데이터를 다루는 PagingDataAdapter 를 살펴보자.</p><pre>class BindingPagingDataAdapter&lt;T : BindableUIModel&gt;(<br>    private vararg val binderBuilders: BinderBuilder<br>) : PagingDataAdapter&lt;T, BindingViewHolder&gt;(createDiffer()) {<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingViewHolder {<br>        return createBindingViewHolder(parent, viewType, binderBuilders.toList())<br>    }<br><br>    override fun onBindViewHolder(holder: BindingViewHolder, position: Int) {<br>        getItem(position)?.let {<br>            holder.bind(it, position)<br>        }<br>    }<br><br>    override fun onBindViewHolder(<br>        holder: BindingViewHolder,<br>        position: Int,<br>        payloads: MutableList&lt;Any&gt;<br>    ) {<br>        if (payloads.isEmpty()) {<br>            super.onBindViewHolder(holder, position, payloads)<br>        } else {<br>            getItem(position)?.let {<br>                holder.bind(it, position, payloads)<br>            }<br>        }<br>    }<br><br>    override fun getItemViewType(position: Int): Int {<br>        return getItem(position)?.layoutId ?: error(&quot;cannot find item at $position&quot;)<br>    }<br><br>}</pre><ul><li>BinderBuilder : 데이터를 어떤식으로 뷰홀더에 바인딩 할 것인지 알려주는 ViewHolderBinder를 만드는 빌더이다. 아래에서 자세히 설명한다.</li><li>BindingViewHolder : 일반화한 뷰홀더이다. 아래에서 설명한다.</li></ul><p>무척이나 간단한 구현이다. 눈여겨 볼 것은 BindableUIModel의 layoutId 를 그대로 viewType으로 사용한다는 점이다.</p><p>다음은 ViewHolder를 살펴보자.</p><pre>class BindingViewHolder(<br>    private val binding: ViewDataBinding,<br>    private val binder: ViewHolderBinder<br>) : ViewHolder(binding.root) {<br><br>    init {<br>        binder.initialize(binding)<br>    }<br><br>    fun bind(item: BindableUIModel, itemPosition: Int, payload : List&lt;Any&gt; = emptyList()) {<br>        binder.bind(binding, item, itemPosition, payload)<br>    }<br><br>}<br><br>fun createBindingViewHolder(<br>    parent: ViewGroup, @LayoutRes layoutId: Int, binderBuilderList: List&lt;BinderBuilder&gt;<br>): BindingViewHolder {<br>    val binding = parent.createViewDataBinding&lt;ViewDataBinding&gt;(layoutId).apply {<br>        lifecycleOwner = parent.findViewTreeLifecycleOwner()<br>    }<br>    val binderBuilder = binderBuilderList.find { it.canBind(binding) }<br>    return BindingViewHolder(binding, binderBuilder?.build() ?: DefaultBinder())<br>}</pre><p>BindingViewHolder 는 바인딩클래스와 ViewHolderBinder를 가지고 있고 ViewHolderBinder에 초기화와 바인딩 로직을 위임하고 있다.</p><pre>interface ViewHolderBinder {<br><br>    fun initialize(viewDataBinding: ViewDataBinding) {}<br><br>    fun bind(<br>        viewDataBinding: ViewDataBinding,<br>        model: BindableUIModel?,<br>        position: Int,<br>        payload: List&lt;Any&gt;<br>    )<br><br>}</pre><p>ViewHolderBinder는 데이터를 UI에 어떻게 바인딩할 것인지를 정의하는 인터페이스이다.</p><pre>class DefaultBinder : ViewHolderBinder {<br>    override fun bind(<br>        viewDataBinding: ViewDataBinding,<br>        model: BindableUIModel?,<br>        position: Int,<br>        payload: List&lt;Any&gt;<br>    ) {<br>        model?.also(viewDataBinding::bind)<br>    }<br>}<br><br>fun &lt;Item : BindableUIModel&gt; ViewDataBinding.bind(item: Item) {<br>    setVariable(item.bindingVariableId, item)<br>    executePendingBindings()<br>}</pre><p>DefaultBinder 에서는 그냥 데이터가 null이 아닐 경우 바인딩 클래스에 데이터를 바인딩해주고 있다.</p><p>끝이다. 이제 사용해보자.</p><pre>class GetSectionUseCase @Inject constructor() : () -&gt; List&lt;Section&gt; {<br>    override fun invoke(): List&lt;Section&gt; {<br>        return listOf(<br>            Section.Horizontal(id = 1, title = &quot;Section Horizontal&quot;),<br>            Section.Vertical(id = 2, title = &quot;Section Vertical&quot;),<br>            Section.Grid(id = 3, title = &quot;Section Grid&quot;)<br>        )<br>    }<br>}</pre><pre>@HiltViewModel<br>class MainViewModel @Inject constructor(<br>    private val getSectionUseCase: GetSectionUseCase<br>) : ViewModel() {<br><br>    val sectionList = Pager(<br>        config = PagingConfig(pageSize = 5, initialLoadSize = 15)<br>    ) {<br>        SectionPagingSource(getSectionUseCase)<br>    }.flow.cachedIn(viewModelScope)<br>}</pre><pre>@AndroidEntryPoint<br>class MainActivity : AppCompatActivity() {<br><br>    private val binding: ActivityMainBinding by lazy {<br>        DataBindingUtil.setContentView(this, R.layout.activity_main)<br>    }<br><br>    private val viewModel: MainViewModel by viewModels()<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        val sectionAdapter = BindingPagingDataAdapter&lt;Section&gt;()<br>        binding.lifecycleOwner = this<br>        binding.vm = viewModel<br>        binding.rvSection.adapter = sectionAdapter<br><br>        repeatOnStarted {<br>            viewModel.sectionList.collect {<br>                sectionAdapter.submitData(it)<br>            }<br>        }<br>    }<br>}</pre><p>이제 따로 Adapter나 ViewHolder의 구현없이도 RecyclerView에 데이터를 셋팅하는게 가능해졌다.</p><p>참고로, BindingPagingDataAdapter에 바인더를 넘겨주지 않았으므로 DefaultBinder가 사용되어 그저 데이터를 UI에 바인딩하게 된다.</p><p>XML을 보면 단순히 섹션 데이터를 이용해 텍스트뷰에 텍스트를 셋팅하고 있다.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br><br>&lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt;<br><br>    &lt;data&gt;<br><br>        &lt;variable<br>            name=&quot;item&quot;<br>            type=&quot;com.bso112.binder.example.data.Section.Grid&quot; /&gt;<br>    &lt;/data&gt;<br><br>    &lt;androidx.constraintlayout.widget.ConstraintLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;&gt;<br><br>        &lt;TextView<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:gravity=&quot;center&quot;<br>            android:text=&quot;@{item.title}&quot;<br>            android:textColor=&quot;@color/black&quot;<br>            android:textSize=&quot;20sp&quot;<br>            android:textStyle=&quot;bold&quot;<br>            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>            tools:text=&quot;Grid&quot; /&gt;<br><br>    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;<br>&lt;/layout&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a9ef21031f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[APK를 자동으로 구워보자]]></title>
            <link>https://medium.com/@bso11246/apk%EB%A5%BC-%EC%9E%90%EB%8F%99%EC%9C%BC%EB%A1%9C-%EA%B5%AC%EC%9B%8C%EB%B3%B4%EC%9E%90-edec6c8fd665?source=rss-2c7333267a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/edec6c8fd665</guid>
            <dc:creator><![CDATA[Tim]]></dc:creator>
            <pubDate>Tue, 11 Oct 2022 11:11:13 GMT</pubDate>
            <atom:updated>2022-10-11T11:13:17.078Z</atom:updated>
            <content:encoded><![CDATA[<p>하이브리드앱 유지보수 업무를 하다보면 QA 나 PO, 웹개발자에게서 웹뷰가 특정 URL을 바라보는 앱을 발행해달라는 요청을 상당히 자주 받게된다.</p><blockquote><strong>이번에 A 피쳐 개발을 완료했는데 단위 QA를 위해서 프론트는 Dev3로, 백엔드는 Dev로 APK 발행해주세요</strong></blockquote><p>하이브리드앱은 기반이 웹이다보니 DEV, STAGING, RELEASE 등 여러 개발환경이 존재하기 때문이다.</p><p>이런 요청때마다 안드로이드 스튜디오를 열어서 특정 브랜치로 체크아웃하고 웹뷰의 HOST URL을 바꾸고 빌드한 후 슬랙으로 전달하는 과정은 너무 번거로웠다.</p><p>이를 자동화 하기위해 젠킨스를 이용하기로 했다.</p><p>젠킨스의 빌드 유발옵션에는 ‘<strong>빌드를 원격으로 유발 (예: 스크립트 사용)</strong>’이라는 옵션이 있다. 이를 이용하면 post 리퀘스트를 통해 빌드 유발을 할 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDp9mv2EbeYekrBl0YCyZg.png" /></figure><p>또한 <strong>String Parameter</strong>를 젠킨스에 전달할 수도 있어서 하나의 젠킨스 프로젝트만 만들면 넘어오는 프로퍼티에 따라 브랜치, 웹뷰 URL을 다르게 설정할 수도 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvRtjFp64_kF114ol7YVWA.png" /></figure><p>예를들어 안드로이드 프로젝트의 그래들에 buildType을 설정해 놓았다면 assembleDebug, assembleRelease 등의 gradle 명령어를 String Parameter로 젠킨스에 넘겨줘서 젠킨스 프로젝트의 Invoke Gradle script 옵션으로 해당 명령어를 실행시킬수도 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d24-PA4SXGO7ag11nn8qUg.png" /></figure><p>빌드할 브랜치 또한 String Parameter로 넘겨주면 Branch Specifier 옵션을 이용해 특정 브랜치를 빌드하도록 할 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBMcJokMgzT1NofC4PRJWQ.png" /></figure><p>빌드시에 웹뷰의 HOST URL을 바꾸는 것은 String Parameter를 통해 젠킨스에서 HOST URL을 받고 Execute Shell 옵션으로 .properties 파일을 생성해서 그 안에 HOST URL을 적은 뒤 안드로이드 프로젝트의 gradle에서 그 프로퍼티 파일을 읽어서 HOST URL을 얻는 식으로 구현했다.</p><p>대략적인 원리는 이상이다.</p><p>필자는 개발 수고를 덜기위해 <strong>플러터로</strong> 앱을 만들어 AOS, IOS 기기 모두에서 사용할 수 있는 앱을 만들었다.</p><p>기능은 별거 없다.</p><ul><li>브랜치 선택</li><li>프론트엔드 HOST URL 선택 (빌드타입 선택)</li><li>백엔드 URL 선택</li><li>슬랙에 APK와 함께 보여줄 메시지 작성</li><li>APK 발행을 알리기 위해 맨션할 사람 검색 및 선택</li></ul><p>이 중에서 슬랙으로 APK를 보내는 것은 젠킨스 프로젝트의 ‘빌드 후 조치’ 옵션을 활용하면 되지만 특정 사람을 멘션하는건 추가적인 수고가 필요하다.</p><p>슬랙 API를 활용해야한다. 필자는 <a href="https://slack.com/api/users.list">https://slack.com/api/users.list</a> 와 <a href="https://slack.com/api/usergroups.list">https://slack.com/api/usergroups.list</a> 를 사용해 슬랙에 있는 멤버와 그룹을 받아오도록 했다.</p><p>이 API를 사용하기 위해선 Slack APP을 만들고 OAuth &amp; Permissions 에서 usergroups:read, users:read 권한을 주어야한다. 권한이 부여된 Slack APP의 토큰을 이용해서 POST 요청을 보내면 결과를 받을 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjGZD4-DQBXDiclBAavjjw.png" /></figure><p>이외에도 보안을 신경써야했다. 아무나가 프로젝트를 빌드할 수 있으면 안되기 때문에 구글 로그인을 추가해 회사 계정으로 로그인한 사람만 앱을 이용할 수 있도록 했다.</p><p>또한 앱에 젠킨스 유저토큰이나 슬랙 유저토큰에 대한 정보를 남기고 싶지 않았기에 Firebase Remote Config를 이용해 API 통신으로 토큰을 받아오도록 했다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*qqC-NM_gLhR6fje1tpgQcw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*sEHKiteXy20ECAvH0_5r1w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*p2FBblOjS_S9ypfaf-6OmA.jpeg" /><figcaption>결과물!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edec6c8fd665" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Koin은 어떻게 동작할까?]]></title>
            <link>https://medium.com/@bso11246/koin%EC%9D%80-%EC%96%B4%EB%96%BB%EA%B2%8C-%EB%8F%99%EC%9E%91%ED%95%A0%EA%B9%8C-eeb9142f179f?source=rss-2c7333267a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeb9142f179f</guid>
            <dc:creator><![CDATA[Tim]]></dc:creator>
            <pubDate>Sat, 21 May 2022 10:46:41 GMT</pubDate>
            <atom:updated>2022-05-21T10:50:55.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*1XViLZ40l08zduNP.png" /></figure><p>의존성 주입 라이브러리를 쓰면서 항상 그 내부가 궁금했다. 도대체 어떤 마법을 부리는 걸까?</p><p>깃허브에서 Dagger 소스코드를 받아 보았지만 너무 복잡했다. Koin은 비교적으로 이해할만해서 Koin을 분석해보기로 했다.</p><p>Koin의 원리를 모두 설명하기엔 너무 길어지기 때문에 이 포스트에서는 Koin을 낱낱히 파헤치는 것이 아닌, 겉핡기식으로 분석해보고자 한다. (사실 이해가 부족해 모두 설명할 수도 없다…)</p><p>일단 다양한 형태의 의존성 주입을 위해서는 <strong>singleton 방식, factory 방식, scoped 방식</strong>으로 인스턴스를 생성해내는 클래스가 각각 필요하다.</p><p>이런 방식을 책임지는 것이 <strong>SingleInstanceFactory, FactoryInstanceFactory, ScopedInstanceFactory</strong> 이다. (부모 클래스는 InstanceFactory 이다)</p><p>이것들을 적절히 저장하고, 가져오기 위해서 Koin은 Module이라는 클래스에서 <strong>해시맵</strong>을 사용한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kp8KyG1S0p4hxT1jCS4lEw.png" /></figure><p>value인 Factory는 언제 생성해서 mappings에 넣어줄까? Koin 문서를 보면 처음에 Module을 생성하는 코드가 나온다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzpJHHC5kV-_vZ66v1_r4w.png" /></figure><p>바로 여기서 그 작업을 수행한다. SingleInstanceFactory&lt;HelloMessageData&gt;를 만들고 적절한 key를 생성해 mappings에 저장한다.</p><p>이제 주입 받는 부분을 살펴보도록 하자.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zps0cu93SFJcQboE-rjR1g.png" /></figure><p>by Inject()의 내부에서는 전에 만들었던 SingleInstanceFactory를 mappings에서 찾아 SingleInstanceFactory가 품고있는 HelloMessageData인스턴스를 가져오게 된다.</p><p>이것이 간략한 흐름이다.</p><p>하지만 여기서 의문점이 생긴다.</p><p><strong>by Inject()는 어떻게 적절한 SingleInstanceFactory를 찾은 것일까?</strong></p><p>module 빌더로 Module을 만들 때로 돌아가보자.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzpJHHC5kV-_vZ66v1_r4w.png" /></figure><p>여기서 SingleInstanceFactory&lt;HelloMessageData&gt;를 생성한다고 했다.<strong> 이 시점에 HelloMessageData 라는 주입할 타입에 대한 정보를 얻게된다.</strong> by Inject() 또한 HelloMessageData라는 타입에 대해서 알기 때문에 mappings에서 적절한 SingleInstanceFactory를 가져올 수 있었다.</p><p><strong>그렇다면 주입받을 수 있는 곳이 스코프로 한정되어있다면 어떨까?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*Jt5tZRhKEzBuo4cBr2V4dQ.png" /></figure><p>scope로 MainActivity에 대한 정보를 주어주고 있다. 그리고 scoped 에서는 Foo라는 타입을 알게된다. <strong>MainActivity, Foo 라는 두 개의 타입 정보를 이용해 key를 생성하고 거기에 Foo 인스턴스를 맵핑하기 때문에</strong> MainActivity에서만 주입된 Foo 인스턴스를 얻어올 수 있는 상태가 된다.</p><p>그럼 주입받는 쪽을 살펴보자.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxfR7o-IhG67cZa-CAAWRg.png" /></figure><p>activityScope()는 LifecycleScopeDelegate를 반환하는데, LifecycleScopeDelegate는 MainActivity의 타입정보를 알고있는 Scope를 생성한다.</p><p><strong>MainActivity가 KoinScopeComponent를 구현하는 것에 주목하자.</strong> by Inject()내부를 살펴보면 아래처럼 호출자가 KoinScopeComponent일 경우 가지고 있는 scope를 찾아내는 것을 알 수 있다. (즉 MainActivity에 선언된 scope)</p><p><strong>이 Scope는 MainActivity에 대해서도, 그리고 by Inject() 으로 인해 Foo에 대해서도 알게된다. </strong>따라서 mappings에서 적절한 InstanceFactory를 찾아 인스턴스를 얻어올 수 있는 것이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kz5DYkO-RasHU3hLDHXf_A.png" /><figcaption>임의로 간략화한 코드이다.</figcaption></figure><p>그럼 MainActivity가 파괴될때 Foo 인스턴스도 파괴하는 건 어떻게 구현했을까?</p><p>방금 activityScope()에서 LifecycleScopeDelegate를 만든다고 했다. LifecycleScopeDelegate는 내부에서 <strong>LifecycleObserver를 통해 lifecycleOwner(여기서는 MainActivity)가 파괴될때 Scope도 파괴하도록 설계되어있다.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3pcvocD8-R4Cm10Oi0Uwg.png" /></figure><p>_scope?.close() 에서는 mappings를 참조하여 scope와 연관된 인스턴스를 모두 삭제한다.</p><p>이렇게 기본적인 Koin의 작동방식에 대해 알아보았다. 생략한 부분이 상당히 많기 때문에 궁금하다면 Koin의 내부를 직접 들여다보는 것을 추천한다!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeb9142f179f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modularization Strategy in Android development]]></title>
            <link>https://medium.com/@bso11246/modularization-strategy-in-android-development-d00bed6bef7f?source=rss-2c7333267a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d00bed6bef7f</guid>
            <dc:creator><![CDATA[Tim]]></dc:creator>
            <pubDate>Sat, 21 May 2022 05:16:46 GMT</pubDate>
            <atom:updated>2022-05-21T05:16:46.226Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBS-U3elv3b5Fg-GUOEazQ.jpeg" /><figcaption>Unsplash@kzzIx1XowGA</figcaption></figure><p>When you implement a new feature in your app, it’s better to modularize implementation than write all your code on activity.</p><p>In this post, I will introduce three methods to modularize business logic on Activity or Fragment to separate class.</p><h4>LifecycleObserver</h4><p>If you have some code run on Activity’s lifecycle callback method, and it’s not necessarily on Activity, then you can try LifecycleObserver. if you have code like the below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u71yBfFZnJhjRDcuWafclQ.png" /></figure><p>You can simply move your code to LifecycleObserver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hd9U_bf_5ZluAoKM7iaaVg.png" /></figure><h4>SavedStateRegistry</h4><p>If your module should save&amp;restore its state when the system kills its process, use SavedStateRegistry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fc-Ln-LRSGHR5If3bSVvBg.png" /></figure><p>This code could be changed to the code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1XZdATVy_J3eW03iwCpwQ.png" /></figure><p>For more detail about the lifecycle, see <a href="https://developer.android.com/topic/libraries/architecture/lifecycle">this</a></p><h4>Activity Result API</h4><p>Using Activity Result API, you can move your code on onActivityResult to your module. In addition, you don’t need to make requestCode for startActivityForResult().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WV6LU7k6fPYNMs7uRT1Pfw.png" /></figure><p>With Activity Result API, you can modularize this code like the below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33d4_HQv6Cqv5xSMVS9F8Q.png" /></figure><p>Also, you can create a custom ActivityResultContract. It’s useful for modularizing your business logic. For example, with CustomTakePicture, you don’t need to have a reference for a file for saving a picture taken by the camera app. CustomTakePicture class handles all of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IaTUpfUZtvsSUYChxkdpg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d00bed6bef7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>