Kotlin에서 콜백을 코루틴으로 변환하는 방법

강현석·2022년 11월 15일
1

article

목록 보기
1/9

본 내용은 학습을 위해 Callback to Coroutines in Kotlin 을 보고 정리한 글입니다.


도입

Library.doSomething(object : Listener {
	
    override fun onSuccess(result: Result) {
    }
    
    override fun onError(throwable: Throwable) {
    }
    
})
  • onSuccess와 onError 콜백이 있는 상태

코루틴으로 변환해보자

suspend fun doSomething(): Result { // 1
	return suspendCoroutine { continuation -> // 2
    		Library.doSomething(object : Listener {
            
            		override fun onSuccess(result: Result) {
                    	continuation.resume(result) // 3
                    }
                    
                    override fun onError(throwable: Throwable) {
                    	continuation.resumeWithException(throwable) // 4
					}
                    
            })
    }
}
  1. Result를 리턴하는 suspend 추가
  2. return 블록에 suspendCoroutine 사용
  3. onSuccess에는 continuation.resume(result) 사용
  4. onError에는 continuation.resumeWithException(throwable) 사용

이와 같이 적용하면, 아래와 같이 호출이 가능함

launch {
	val result = doSomething()
}

취소 기능을 지원해보자

아래와 같은 함수로 "취소"를 하는 기능이 있다고 가정

Library.cancel(id)

적용해보면?

suspend fun doSomething(): Result {
    return suspendCancellableCoroutine { continuation -> // 1
        val id = Library.doSomething(object : Listener {

            override fun onSuccess(result: Result) {
                continuation.resume(result)
            }

            override fun onError(throwable: Throwable) {
                continuation.resumeWithException(throwable)
            }

        })

        continuation.invokeOnCancellation { // 2
            Library.cancel(id)
        }
    }
}
  1. suspendCoroutin 대신 suspendCancellableCoroutine 사용
  2. "취소"를 하는 기능을 continuation.invokeOnCancellation 블록 내부에서 호출

이와 같이 적용하면, 아래와 같이 호출이 가능함

launch {
	val result = doSomething()
}
profile
볼링을 좋아하는 안드로이드 개발자

0개의 댓글