Search code examples
androidkotlincallback

How can I return value from callback in Kotlin?


How can I send the result to the ViewModel in this case???

val callback: (OAuthToken?, Throwable?) -> Unit = { token, error ->
    if (error != null) {
        // TODO: error return to viewModel
    } else if (token != null) {
        // TODO: success return to viewModel
    }
}

fun signInWithABC() {
    abcApi.signIn(callback = callback)
}

I think signInWithABC should returns to the ViewModel, not from callback directly... maybe like this..

fun signInWithABC(): Result<AuthData> {
    return abcApi.signIn(callback = callback)
}

But, I don't know how to do it..

Should I fix it like this? It doesn't look clean though.

fun signInWithABC() {
    abcApi.signIn(){ token, error ->
        if (error != null) {
            // TODO: error return to viewModel
        } else if (token != null) {
            // TODO: success return to viewModel
        }
    }
}

And I also tried it with this.. but it has return problem. lamda can't return the value for the function. But it can only return for the block..

fun signInWithABC(): Result<String> {
    abcApi.signIn(){ token, error ->
        if (error != null) {
            return Result.failure<Throwable>(error)
        } else if (token != null) {
            return Result.success(token)
        }
    }
    return Result.failure(throw IllegalAccessException())
}

Solution

  • You may need to do callback to suspend conversion. Here is a simple example of doing this:

    suspend fun signInWithABC(): String = suspendCoroutine { continuation -> 
        abcApi.signIn(){ token, error ->
            if (error != null) {
                continuation.resume("Error")
            } else {
                continuation.resume(token) // Assuming token is a string
            }
        }            
    }