简体   繁体   English

Kotlin:等待异步调用完成,然后将值分配给 var 然后返回

[英]Kotlin: wait for Async call to finish and then assign value to var and then return it

I have a variable loginToken .我有一个变量loginToken I want to assign value to is as我想赋值为

var loginToken: String = getLoginToken()

Following is my getLoginToken function以下是我的getLoginToken function

private fun getLoginToken(context: Context): String {
    val sharedPref: SharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
    var token =  sharedPref.getString("token", null)
    if (token == null) {
        token = LoginManager(activity).getToken(onGetSuccess = {
                // I get token here, i want to assign it to token var
             }, onGetFailure = {
                // I want to set token as empty string
             })
    }
    return token
}

How should I assign value to token and finally return it only when I get the result of getToken call?我应该如何为token赋值并最终在我得到 getToken 调用的结果时才返回它?

You can use suspendCancellableCoroutine to convert a callback approach to coroutines.您可以使用suspendCancellableCoroutine将回调方法转换为协程。 So for a coroutine approach, we can do something like this:所以对于协程方法,我们可以这样做:

private fun getLoginToken(context: Context): String {
    val sharedPref: SharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
    var token = sharedPref.getString("token", null)
    if (token == null) {
        token = runBlocking { getTokenFromActivity(activity) }
    }
    return token
}

private suspend fun getTokenFromActivity(activity: Activity) =
    suspendCancellableCoroutine {
            LoginManager(activity).getToken(onGetSuccess = {
                it.completeResume(result)
            }, onGetFailure = {
                it.completeResume("")
            })
        }

You can also use a locking approach.您还可以使用锁定方法。 For example, using a CountdownLatch .例如,使用CountdownLatch (lock it before the getToken function and unlock when the result is ready in the callback.) (在getToken function 之前锁定它,并在回调中准备好结果时解锁。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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