suspend 함수에서 async가 깨질 때, 고려해야할 점들

참치돌고래·2022년 12월 2일
0

가령 user 정보를 불러오고, db에 조회정보를 다시 notify하는 함수가 있다고 해보자

class UserService(
    private val repo : UserDataRepository,
    private val sender : Sender
){
    suspend fun showUserData() = coroutineScope { 
        val name = async { repo.getName()}
        val friends = async { repo.getFriends() }
        val profile = async { repos.getProfile() }
        val user = User(
            name = name.await(),
            friends = name.await(),
            profile = name.await()
        )
        sender.send(user)
        launch { repo.notifyProfile() }
    }
}

위의 코드는 launch 가 완료된 후에야 send가 작동하게 될 것이다.
또한 cancellation 발생 시에도 문제점이 발생한다.
마지막, launch {repo.notifyProfile()}에서 에러가 발생하게되면 위의 로직들 역시 모두
exception이 전파되어 cancel된다.

해결책

val analyticsScope = CoroutineScope(SupervisorJob())

class UserService(
    private val repo : UserDataRepository,
    private val sender : Sender,
    private val analyticsScope : CoroutineScope
){
    suspend fun showUserData() = coroutineScope { 
        val name = async { repo.getName()}
        val friends = async { repo.getFriends() }
        val profile = async { repos.getProfile() }
        val user = User(
            name = name.await(),
            friends = name.await(),
            profile = name.await()
        )
        sender.send(user)
        analyticsScope.launch { repo.notifyProfile() }
    }
}

profile
안녕하세요

0개의 댓글