Android Compose Ktor

사용 언어: Kotlin 1.9.22
사용 버전: Android Studio 2023.1.1 Patch 1


안드로이드 컴포즈 Ktor를 알아보겠습니다.



Ktor는 Server와 통신하는 것을 도와주는 프레임워크입니다. 특이한 것은 Server와 Client 모두 사용 가능하다는 것입니다.
Ktor는 JetBrain에서 공식적으로 지원하고 있으며 Kotlin으로 이루어졌습니다.


Retrofit이 적용된 프로젝트에 Ktor로 변경하는 과정을 같이해봅시다.
참고 프로젝트:
https://github.com/Jaehwa-Noh/Practice-Amphibians/tree/compose-ktor-amphibians-app



App 용 Build.gradle에 dependencies를 추가해 줍니다.

implementation("io.ktor:ktor-client-content-negotiation:2.3.7")

implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.7")

implementation("io.ktor:ktor-client-core:2.3.7")

implementation("io.ktor:ktor-client-okhttp:2.3.7")

implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2")






network 밑에 AmphibiansKtorApiService를 만듭니다.







install에 ContentNegotiation을 적어줍니다.

Text.Plain을 Json으로 변경할 것을 알려주고, ignoreUnknownKeys는 정의되지 않은 Key가 있으면 무시하겠다는 겁니다.

defaultRequest는 기본 url 설정입니다.

expectSuccess는 통신 성공을 예상한다는 뜻입니다.

AmphibiansKtorApiService.kt









Qualifier를 만들어주고, provideKtorAmphbiansApi 함수를 만들어줍니다.

원래는 필요 없지만, 여기서는 Retrofit과 섞여있어서 이렇게 만들어줍니다. 나중에는 지워줄 겁니다.

AmphibiansApiModule.kt







amphibiansKtorAPI를 추가해 주고 사용해 줍니다.

AmphibiansRemoteDataSource.kt








실행해 봅시다.








잘 실행되네요.



이제, Retrofit 관련 파일들을 지워줍니다.

implementation("com.squareup.okhttp3:okhttp:4.12.0")

implementation("com.squareup.retrofit2:retrofit:2.9.0")

implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:1.0.0")






아래의 파일을 삭제합니다.

AmphibiansApiService.kt






abstract class로 변경하고 Binds를 해줍니다.

AmphibiansApiModule.kt






Qualifier를 제거해 줍니다.

AmphibiansRemoteDataSource.kt








ResponseException으로 변경해 줍니다.

AmophibiansViewModel.kt







다시 실행해 봅시다.




Retrofit을 Ktor로 Migration 해보았습니다.





끝.


카테고리: Android, Compose



댓글

이 블로그의 인기 게시물

Python urllib.parse.quote()

Python bytes.fromhex()

Python OpenCV 빈 화면 만들기

Android Notification with Full Screen

Android Minimum touch target size

Android Compose Instrumentation test to unit test

tensorflow tf.expand_dims()

KiCad 시작하기 7 (FreeRoute 사용하기 2)

딩기 요트 명칭

Forensics .pyc 파일 .py로 복구하기