안드로이드/기타
비동기 작업의 결과값을 동기적으로 반환받는 방법 2가지
안드뽀개기
2023. 11. 8. 09:58
반응형
외부와 통신을 하는 로직을 만들기 위해서는 비동기적인 로직이 필요합니다.
하지만, 가끔 비동기 함수를 호출하고 반환된 결과값을 받아 연속적으로 다음 로직을 실행하도록 하고 싶을때가 있습니다.
그럴때 사용할 수 있는 방법은 두 가지가 있습니다.
1. CompletableFuture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun getAuthUser(): AuthUser? { | |
val completableFuture = CompletableFuture<AuthUser>() | |
Amplify.Auth.getCurrentUser( | |
{ authUser -> completableFuture.complete(authUser) }, | |
{ exception -> completableFuture.completeExceptionally(exception) } | |
) | |
return try { | |
completableFuture.get() | |
} catch (e: Exception) { | |
// 오류 처리 | |
null | |
} | |
} |
2. suspendCoroutine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
suspend fun getAuthUser(): AuthUser? { | |
return suspendCoroutine { continuation -> | |
Amplify.Auth.getCurrentUser( | |
{ authUser -> continuation.resume(authUser) }, | |
{ exception -> continuation.resume(null) } | |
) | |
} | |
} |
반응형