반응형
외부와 통신을 하는 로직을 만들기 위해서는 비동기적인 로직이 필요합니다.
하지만, 가끔 비동기 함수를 호출하고 반환된 결과값을 받아 연속적으로 다음 로직을 실행하도록 하고 싶을때가 있습니다.
그럴때 사용할 수 있는 방법은 두 가지가 있습니다.
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) } | |
) | |
} | |
} |
반응형
'안드로이드 > 기타' 카테고리의 다른 글
EditText - MultiLine과 IME_ACTION_DONE 함께 쓰기 (0) | 2023.09.11 |
---|---|
[안드로이드] DiffUtil의 동일성과 동등성에 대한 이해 (0) | 2022.04.08 |
[안드로이드] 안드로이드 스튜디오 범블비 업데이트 이후 Gradle 변경사항 (0) | 2022.04.03 |
[안드로이드] RecyclerView 아이템이 서서히 나타나는 애니메이션(LayoutAnimation) (0) | 2022.03.31 |
[안드로이드] 디바이스 가로/세로 길이 구하기 (0) | 2022.03.29 |