简体   繁体   中英

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())
    }

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
            }
        }            
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM