<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>cha_min.log</title>
        <link>https://velog.io/</link>
        <description>안드로이드 개발 공부 일지</description>
        <lastBuildDate>Fri, 06 Oct 2023 08:58:00 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>cha_min.log</title>
            <url>https://velog.velcdn.com/images/cha_min/profile/cc30ab24-d9c7-4983-bddd-4c66c4f9297d/social_profile.png</url>
            <link>https://velog.io/</link>
        </image>
        <copyright>Copyright (C) 2019. cha_min.log. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/cha_min" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[Coroutine 이란 뭘까?]]></title>
            <link>https://velog.io/@cha_min/Coroutine-%EC%9D%B4%EB%9E%80-%EB%AD%98%EA%B9%8C</link>
            <guid>https://velog.io/@cha_min/Coroutine-%EC%9D%B4%EB%9E%80-%EB%AD%98%EA%B9%8C</guid>
            <pubDate>Fri, 06 Oct 2023 08:58:00 GMT</pubDate>
            <description><![CDATA[<h2 id="coroutine-이란-">Coroutine 이란 ?</h2>
<p> 안드로이드 개발을 하다보면 이 코루틴이라는 녀석을 자주보고 또 자주 사용하게 된다. 코루틴은 kotlin 에서만 사용하는것 같지만 실제로 파이썬, C#, Go, Javascript 등 여러 언어에서 지원하고 있다. Javascript 의 asynce await 와 같은 개념이라고 보면된다. 코루틴이란 쉽게 말해 동시성 프로그래밍의 개념을 Kotlin 에 적용한것이라고 보면된다. 우리는 일반적으로 &quot;비동기 처리&quot;를 할때 코루틴을 사용한다. 비동기 처리란건 뭘까 ?</p>
<h2 id="비동기처리">비동기(처리)?</h2>
<p> 우리들이 일반적으로 코드를 실행할때 , 작성한 코드가 순서대로 처리 되곤한다. 이러한 작업은 동기라고한다. 한번에 하나의 일만 실행되는 경우이다. 그렇다면 비동기란 여러개의 작업을 동시에 처리 하는 것을 말한다.
 일반적으로 우리가 코드에서 이러한 비동기처리를 사용하는 곳은 대부분 코드에서 처리시간이 오래걸리는 작업이다. DB 에 데이터를 추가 삭제하는 작업이나 혹은 Rest API 를 통한 통신으로 응답이 올때까지 기다려야하는 작업의 경우 비동기처리를 하지않는다면 해당작업이 끝날때까지 하루종일 앱이 멈춰있게 된다. 이러한 문제점을 해결해주기 위해 coroutine 을 이용해 Main Thread 가 아닌 다른 Thread 에서 작업을 처리해주며 동시에 작업을 처리해주는 것이다.</p>
<h2 id="코루틴-활용">코루틴 활용</h2>
<p>자 이제 코루틴을 사용해보자</p>
<blockquote>
<pre><code>dependencies {
    implementation &#39;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9&#39;
}</code></pre></blockquote>
<p>우선 Gradle 에 추가를 해줘야한다 . </p>
<pre><code>CouroutineScope.launch(Dispatchers.Main) {
    //JOB 
}</code></pre><p><strong>launch ?</strong>
launch 를 통해서 corountine 의 block 을 만든다. 현재 Thread 를 차단하지않고 새로운 coroutine 을 실행할 수 있다 !</p>
<p>GlobalScope 과 Coroutine Scope 의 차이는 Global 은  앱이 실행될 때 부터 종료될 때 까지 코루틴을 실행시키고 , Coroutine Scope를 Activity의 LifeCycle에 맞춰주면 Activity가 종료될 때 코루틴도 함께 종료되도록 만들 수 있다.</p>
<p>스레드의 종류에는 3가지가 있다. 
Main : 메인 스레드, 화면 ui 작업 등을 하는 곳
IO : 네트워크, DB 등 백그라운드에서 필요한 작업을 하는 곳
Default : 정렬이나 무거운 계산 작업 등을 하는 곳
코루틴을 통해 다른 Thread 에서 작업을 실행하며 어플리케이션을 효율적으로 실행할 수 있다.</p>
<p>자 이제 각 Thread에 맞는 job 을 배치해주면 된다. suspend 함수를 활용하면 더욱 효율적으로 활용이 가능하다 .</p>
<p><strong>suspend ?</strong>
suspend 함수란 &quot;일시 중단 가능한 함수&quot; 이다.
하나의 thread 가 block 될때 , 그 thread 는 다른 작업을 할 수 없다. 하지만 suspend 함수를 사용한다면 block 된 상태 인경우 해당 작업을 suspend 하고 그 동안 thread 에서 다른 작업을 사용할 수 있다 ! 따라서 하나의 thread 에서 여러개의 coroutine 을 실행 할 수 있는 것이다 .thread 자원을 아주 효율적으로 쓸 수 있는것이다.</p>
<p>자세한 내용은 안드로이드 공식문서를 참조하면 좋다 .
<a href="https://developer.android.com/kotlin/coroutines?hl=ko">링크텍스트</a></p>
<p>완전 기초적인 내용만 써두었기 때문에 async , runblocking , coroutine context 등등 다루지 않은 것이 많다 . to be continue ... </p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Gradle Kotlin / Gradle Groovy ?]]></title>
            <link>https://velog.io/@cha_min/Gradle-Kotlin-Gradle-Groovy</link>
            <guid>https://velog.io/@cha_min/Gradle-Kotlin-Gradle-Groovy</guid>
            <pubDate>Thu, 06 Jul 2023 08:27:17 GMT</pubDate>
            <description><![CDATA[<p>여태까지 안드로이드 스튜디오를 사용하면서 막연히 이 기능 쓰려면 gradle 에 라이브러리 implement 해야지 .. 라는 생각만 했었는데 이번에 기초부터 다져야겠다는 생각에 이 gradle 이 무엇일까 ? 부터 공부해보기로 했다 . </p>
<h3 id="buildgradle-이란-무엇일까-">build.gradle 이란 무엇일까 ?</h3>
<p>Gradle 이란 Groovy , Kotlin 을 기반으로 한 빌드 배포 도구이다. 우리가 사용하는 안드로이드 스튜디오는 코드 편집만이 가능한 IDE(Integrated Development Environment) 환경이기때문에 Gradle 을 사용한다 .</p>
<p>gradle 파일은 원래 Groovy DSL을 주로 사용했지만 점점 Kotlin DSl 사용을 권장하는 추세이다.</p>
<h3 id="gradleproject--gradlemodule-의-차이점-">gradle(Project) , gradle(Module) 의 차이점 ?</h3>
<img src="https://velog.velcdn.com/images/cha_min/post/7abdcccc-c1df-4e54-bbc6-5d25872a149a/image.PNG" height="100px" width="300px">
안드로이드 스튜디오에서 항상 우리를 반겨주던 Gradle 들이다 . 별다른 모듈 설정을 하지 않았다면 위의 그림같이 나타날 것이다 . 
쉽게 생각해서 build.gradle(Project) 는 모든 프로젝트에 공통으로 적용되는 빌드의 구성을 정의하고 , build.gradle(Module) 은 각각의 개별 모듈에서 적용되는 빌드 구성을 정의한다 .

<h4 id="buildgradleproject">build.gradle(Project)</h4>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath &quot;com.android.tools.build:gradle:7.0.4&quot;
        classpath &#39;org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.21&#39;

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}</code></pre><h4 id="buildgradlemodule">build.gradle(Module)</h4>
<pre><code>plugins {
    id &#39;com.android.application&#39;
    id &#39;kotlin-android&#39;
    id &#39;kotlin-android-extensions&#39;
}

android {
    compileSdk 32

    buildFeatures{
        viewBinding true
    }


    defaultConfig {
        applicationId &quot;com.example.infrastudy&quot;
        minSdk 30
        targetSdk 32
        versionCode 1
        versionName &quot;1.0&quot;

        testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = &#39;1.8&#39;
    }
}

dependencies {
    implementation &#39;com.squareup.retrofit2:retrofit:2.5.0&#39;
    implementation &#39;com.google.code.gson:gson:2.8.2&#39;
    implementation &#39;com.squareup.retrofit2:converter-gson:2.4.0&#39;
    implementation &#39;androidx.core:core-ktx:1.7.0&#39;
    implementation &#39;androidx.appcompat:appcompat:1.4.1&#39;
    implementation &#39;com.google.android.material:material:1.5.0&#39;
    implementation &#39;androidx.constraintlayout:constraintlayout:2.1.3&#39;

}</code></pre><p>안의 세부 내역을 살펴보면 ,
plugins{} : 안드로이드 전용 빌드 옵션
android{} : 모든 안드로이드 관련 설정</p>
<p>compileSdk : Android API 레벨. (해달 레벨 이하 이용 가능)</p>
<p>minSdk : 최소 API 레벨.
targetSdk : 테스트에 사용하는 API 레벨
buildTypes{} : 빌드 타입 종류 지정 (release, develoption, staging.. 등등)
dependencies{} : 특정 버전을 선택해서 라이브러리 추가 
의 의미를 가진다 .</p>
<p>위의 코드들은 모두 Groovy DSL 을 기준으로 하고 있는데 , 요즘은 Kotlin DSL 을 많이 사용하는 추세라고 한다 . Groovy 와 Kotlin DSL 에는 어떤 차이점이 있을까 ? </p>
<h3 id="groovy-에서-ktskotlin-스크립트-로의-빌드-구성-이전">Groovy 에서 KTS(Kotlin 스크립트) 로의 빌드 구성 이전</h3>
<p>위에서는 Kotlin DSL 이라고 했는데 왜 여기선 KTS 라고 썼을까 ? Android 개발자 문서에서 Groovy 에서 이전하는 맥락에서는 KTS로 변환하는것과 Kotlin DLS로 변환하는게 같은 의미라고 한다 .</p>
<p>아무튼 , 기존 Groovy 에서 KTS 로 변환하는 이유에 대해 간단하게 알아보자
<strong>1. &quot;에러 확인&quot; **
이게 사실 상 가장 큰 메리트라고 할 수 있다 . 기존의 Groovy 방식에서는 빌드를 하기전엔 확인이 불가능 했는데 컴파일 타임에 에러확인이 가능해진다 .
**2. 코드 탐색 및 자동 완성</strong>
<strong>3. 구문 강조</strong>
<strong>4. IDE 지원으로 향상된 편집환경</strong>
등등의 편의성이 생긴다 . 하지만 Java8 이상에서만 동작이 가능하고 , 빌드시의 속도가 Groovy 보다 느리다는 단점이 존재한다 . </p>
<h3 id="kotlin-dsl-로-migration-하기">Kotlin DSL 로 Migration 하기</h3>
<p>직접 해본결과 비교적 간단하게(?) Migration이 가능했다 . 애초에 build.gradle 파일을 build.gradle.kts 파일로 바꾸고 문법들만 수정해주면 된다 . </p>
<h4 id="1-settinggradle-파일-바꾸기">1. setting.gradle 파일 바꾸기</h4>
<p>파일 명을 setting.gradle.kts 로 수정하고 해당부분만 수정을 해주면된다 . Kotlin 으로 수정할때 기억해야 할 핵심은 ( ) 와 &quot;&quot; 이다 . Groovy 의 경우 &#39;&#39; 의사용이 많은데 kotlin 으로 Migration 할경우 이 작은 따옴표를 큰따옴표로 모두 바꿔줘야한다 .</p>
<img src="https://velog.velcdn.com/images/cha_min/post/42ae0de3-6c16-4832-91f8-b5994a69529e/image.png" height="100px" width="300px">

<h4 id="2-프로젝트-buildgradle-파일-바꾸기">2. 프로젝트 build.gradle 파일 바꾸기</h4>
<p>다음은 프로젝트의 build.gradle 파일을 build.gradle.kts 로 바꿔주고 내부 문법을 수정해준다 . 내 버전에 프로젝트 build.gradle 파일은 코드가 좀 달라서 다음과 같이 바꿔주었다 . </p>
<p><img src="https://velog.velcdn.com/images/cha_min/post/b8867cf6-35a2-40f8-a58f-be8cd3f9be95/image.png" alt=""></p>
<h4 id="3-모듈-buildgradle-파일-바꾸기">3. 모듈 build.gradle 파일 바꾸기</h4>
<p>다음은 모듈의 build.gradle 파일을 build.gradle.kts 로 바꾸고 내부 문법을 수정해준다 . 이 부분이 고칠부분이 가장많아서 조금 까다롭다 . 기존의 groovy 문법으로 되어있는 파일을 kotlin 문법으로 수정해주면 된다 .
<img src="https://velog.velcdn.com/images/cha_min/post/22707d97-b3e1-4e7a-9a9a-d67be60323d6/image.png" alt=""></p>
<pre><code>plugins {
    id (&quot;com.android.application&quot;)
    id (&quot;org.jetbrains.kotlin.android&quot;)
}

android {
    namespace =&quot;com.example.myapplication&quot;
    compileSdkVersion(32)

    defaultConfig {
        applicationId =&quot;com.example.myapplication&quot;
        minSdkVersion(21)
        targetSdkVersion(32)
        versionCode =1
        versionName =&quot;1.0&quot;

        testInstrumentationRunner =&quot;androidx.test.runner.AndroidJUnitRunner&quot;
    }

    buildTypes {
       getByName(&quot;release&quot;) {
            isMinifyEnabled = false // groovy 와 사용법이 좀 다르다
            proguardFiles(getDefaultProguardFile(&quot;proguard-android-optimize.txt&quot;), &quot;proguard-rules.pro&quot;)
        }
    }
    compileOptions {
        sourceCompatibility=JavaVersion.VERSION_1_8
        targetCompatibility=JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = &quot;1.8&quot;
    }
}

dependencies {

    implementation (&quot;androidx.core:core-ktx:1.7.0&quot;)
    implementation (&quot;androidx.appcompat:appcompat:1.6.1&quot;)
    implementation (&quot;com.google.android.material:material:1.9.0&quot;)
    implementation (&quot;androidx.constraintlayout:constraintlayout:2.1.4&quot;)
    testImplementation (&quot;junit:junit:4.13.2&quot;)
    androidTestImplementation (&quot;androidx.test.ext:junit:1.1.5&quot;)
    androidTestImplementation (&quot;androidx.test.espresso:espresso-core:3.5.1&quot;)
}</code></pre><p>이게 Kotlin 문법으로 수정한 build.gradle.kts 코드이다 . 중간에 isMinifyEnabled 이 변수명이 달라져서 해당부분을 수정해줘야한다 . 그리고 buildtypes 을 getByName 을 통해 가져온다는 점도 약간 다르다 . 나머지 부분은 위에서 설명했듯이 ( ) 와 &quot;&quot; 만 주의하면 크게 문제없이 바꿀 수 있다 .</p>
<p>이제 Sync 만 하면 끝 ! 비교적 간단하게 Kotlin 으로 바꿀수있어서 앞으론 겁내지않고 코틀린으로 바꾸고 프로젝트를 진행할 것 같다 .</p>
]]></description>
        </item>
    </channel>
</rss>