[kotlin] 코루틴을 사용한 간단한 프로젝트 예제

코틀린에서 비동기 처리를 위해 코루틴을 사용하는 방법을 알아보겠습니다. 이 예제에서는 GitHub의 API를 사용하여 사용자의 리포지토리 목록을 가져오는 간단한 프로젝트를 만들어 보겠습니다.

프로젝트 설정

먼저, 코틀린 프로젝트를 만들고 Gradle을 사용하여 다음과 같이 build.gradle.kts 파일에 의존성을 추가합니다.

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.1")
}

사용자의 GitHub 리포지토리 목록 가져오기

다음으로, 사용자의 GitHub 리포지토리 목록을 가져오기 위해 다음과 같이 코드를 작성합니다.

import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers.IO
import okhttp3.*
import java.io.IOException

fun main() {
    runBlocking {
        val username = "사용자명" // 사용자명을 입력합니다.
        val repositories = getGitHubRepositories(username)
        repositories.forEach { repository ->
            println(repository)
        }
    }
}

suspend fun getGitHubRepositories(username: String): List<String> = withContext(IO) {
    val url = "https://api.github.com/users/$username/repos"
    val request = Request.Builder()
        .url(url)
        .build()

    val client = OkHttpClient()
    val response = client.newCall(request).execute()
    val responseBody = response.body?.string()
    response.close()

    if (response.isSuccessful && responseBody != null) {
        // JSON 파싱 및 리포지토리 목록 반환
    } else {
        throw IOException("Error retrieving repositories for user: $username")
    }
}

이 예제에서는 코루틴을 사용하여 백그라운드 스레드에서 네트워크 요청을 수행하고, 결과를 메인 스레드로 반환하여 사용자의 GitHub 리포지토리 목록을 출력합니다.

마치며

이 예제를 통해 코루틴을 사용하여 비동기 작업을 간단하게 처리하는 방법을 살펴보았습니다. 코루틴은 코틀린에서 강력한 비동기 처리 기능을 제공하며, 프로젝트의 복잡성을 줄이고 성능을 향상시킬 수 있습니다.

더 많은 정보는 코틀린 코루틴 공식 문서를 참고하세요.