🚀 왜 코루틴인가?
📖 코루틴이란?
**코루틴(Coroutines)**은 비동기 프로그래밍을 쉽고 직관적으로 만드는 Kotlin의 핵심 기능입니다. 복잡한 콜백 지옥에서 벗어나 마치 동기 코드처럼 작성할 수 있습니다!
💡 전통적인 비동기의 문제
콜백 지옥
// ❌ 콜백 방식 (읽기 어렵고 유지보수 힘듦)
fun fetchUser(userId: String, callback: (User?) -> Unit) {
fetchFromNetwork(userId) { result ->
if (result != null) {
fetchProfile(result.id) { profile ->
if (profile != null) {
fetchPosts(profile.id) { posts ->
callback(User(result, profile, posts))
}
} else {
callback(null)
}
}
} else {
callback(null)
}
}
}
쓰레드의 비용
// ❌ 쓰레드는 비싸다
fun downloadFiles() {
repeat(1000) {
Thread {
// 각 쓰레드는 메모리를 많이 사용
downloadFile("file_$it.txt")
}.start()
}
// 메모리 부족 가능성!
}
✨ 코루틴의 장점
1. 간결한 코드
// ✅ 코루틴 (읽기 쉽고 직관적)
suspend fun fetchUser(userId: String): User? {
val result = fetchFromNetwork(userId) ?: return null
val profile = fetchProfile(result.id) ?: return null
val posts = fetchPosts(profile.id)
return User(result, profile, posts)
}
2. 가벼운 동시성
// ✅ 수천 개의 코루틴도 문제없음
suspend fun downloadFiles() {
coroutineScope {
repeat(10000) {
launch {
// 가벼 운 코루틴!
downloadFile("file_$it.txt")
}
}
}
}
3. 구조화된 동시성
// ✅ 자동으로 생명주기 관리
suspend fun processData() {
coroutineScope {
val job1 = launch { task1() }
val job2 = launch { task2() }
// 모든 작업이 끝나면 자동으로 완료
}
}
🎯 실제 사용 예시
네트워크 요청
// 콜백 없이 깔끔하게!
suspend fun loadUserData(userId: String): UserData {
val user = apiService.getUser(userId)
val posts = apiService.getPosts(userId)
val friends = apiService.getFriends(userId)
return UserData(user, posts, friends)
}