Kotlin 코루틴으로 개조
이번 블로그에서는 Android에서 Kotlin
Retrofit과 함께 Coroutines를 사용하는 방법에 대해 알아보겠습니다. 기본 MVVM 아키텍처를 따르는 KotlinViewModel을 사용하여 Coroutines 내부에 코드를 작성하는 방법을 배웁니다.이 문서는 원래 amitshekhar.me에 게시되었습니다.
구현 부분에 다음 프로젝트를 사용할 것입니다. 이 프로젝트는 단순성을 위해 기본 MVVM 아키텍처를 따릅니다. 프로젝트 자체에서 이 블로그에 언급된 구현을 위한 전체 코드를 찾을 수 있습니다.
GitHub 프로젝트: Learn Kotlin Coroutines
먼저 Retrofit에 대한 종속성을 아래와 같이 설정해야 합니다.
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
참고: 항상 사용 가능한 최신 버전을 확인하십시오.
Gson을 사용하여 JSON을 Java 및 Kotlin 클래스로 구문 분석하므로 Gson에 대한 종속성을 추가했습니다. 요구 사항에 따라 추가할 수 있습니다.
이제 아래와 같이
data 클래스ApiUser를 만듭니다.data class ApiUser(
@SerializedName("id")
val id: Int = 0,
@SerializedName("name")
val name: String = "",
@SerializedName("email")
val email: String = "",
@SerializedName("avatar")
val avatar: String = ""
)
이제 Retrofit에 필요한
ApiService 인터페이스를 생성해야 합니다.interface ApiService {
@GET("users")
suspend fun getUsers(): List<ApiUser>
@GET("more-users")
suspend fun getMoreUsers(): List<ApiUser>
@GET("error")
suspend fun getUsersWithError(): List<ApiUser>
}
참고: 코루틴 또는 다른
suspend 함수에서 호출할 수 있도록 코루틴을 지원하기 위해 suspend 키워드를 사용했습니다.그 후에
RetrofitBuilder 가 될 Singleton 클래스가 필요합니다.object RetrofitBuilder {
private const val BASE_URL = "https://5e510330f2c0d300147c034c.mockapi.io/"
private fun getRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val apiService: ApiService = getRetrofit().create(ApiService::class.java)
}
그런 다음 인터페이스
ApiHelper를 생성합니다.interface ApiHelper {
suspend fun getUsers(): List<ApiUser>
suspend fun getMoreUsers(): List<ApiUser>
suspend fun getUsersWithError(): List<ApiUser>
}
참고: 다시 말하지만, 코루틴이나 다른
suspend 함수에서 호출할 수 있도록 코루틴을 지원하기 위해 suspend 키워드를 사용했습니다.그런 다음
ApiHelperImpl 인터페이스를 구현하는 클래스ApiHelper를 만듭니다.class ApiHelperImpl(private val apiService: ApiService) : ApiHelper {
override suspend fun getUsers() = apiService.getUsers()
override suspend fun getMoreUsers() = apiService.getMoreUsers()
override suspend fun getUsersWithError() = apiService.getUsersWithError()
}
이렇게 하면 아래와 같이
ApiHelper의 인스턴스를 만들 수 있습니다.val apiHelper = ApiHelperImpl(RetrofitBuilder.apiService)
마지막으로, 예를 들어
ViewModel 와 같이 필요할 때마다 이 인스턴스를 전달할 수 있고 아래와 같이 네트워크에서 users 를 가져오기 위해 네트워크 호출을 수행할 수 있습니다.class SingleNetworkCallViewModel(private val apiHelper: ApiHelper, private val dbHelper: DatabaseHelper) : ViewModel() {
init {
fetchUsers()
}
private fun fetchUsers() {
viewModelScope.launch {
try {
val usersFromApi = apiHelper.getUsers()
// list of users from the network
} catch (e: Exception) {
// handle exception
}
}
}
}
이렇게 하면 Android에서 Retrofit with Kotlin
Coroutines을 사용하여 네트워크에서 데이터를 가져올 수 있습니다.이 블로그에서 위에서 언급한 GitHub 리포지토리에서 훨씬 더 많은 것을 배울 수 있음을 언급해야 합니다. 다음을 배울 수 있습니다.
이것이 Android에서 Kotlin 코루틴과 함께 Retrofit을 사용하는 방법입니다.
지금은 그게 다입니다.
감사
Amit Shekhar
다음에서 나와 연결할 수 있습니다.
Read all of my high-quality blogs here.
Reference
이 문제에 관하여(Kotlin 코루틴으로 개조), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/amitiitbhu/retrofit-with-kotlin-coroutines-3nc0텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)