我尝试将异步 Kotlin 方法的结果存储到变量中。
Amplify.Auth.fetchAuthSession(
{result ->
Log.i(TAG, "Amplify: Fetch Auth Session $result")
isAuthenticated = result.isSignedIn
},
{error ->
Log.e(TAG , "Amplify: Fetch Auth Session $error")
}
)
if (isAuthenticated == true) {
[...]
我真的不知道如何将 result.isSignedIn
设置为 isAuthenticated
变量,以便我可以在闭包之外使用它。我在 stackoverflow 上发现了一个类似的问题,但它没有帮助我。
有人可以帮助我吗?!
最佳答案
你在这里做什么(就在 lambda 中保存值而言)在技术上是正确的,但在功能上 - 不一定:值在 lambda 更新之前使用。
考虑从回调 lambda 开始进一步的逻辑,您会在其中收到 result
。
请参阅下面的代码 fragment 以获得更好的概述:
Amplify.Auth.fetchAuthSession(
{result ->
Log.i(TAG, "Amplify: Fetch Auth Session $result")
handleResult(result.isSignedIn)
},
{error ->
Log.e(TAG , "Amplify: Fetch Auth Session $error")
}
)
} // end of the method with the async call
fun handleResult(isAuthenticated: Boolean) {
// here goes the code that consumes the result
if (isAuthenticated) {
// ...
}
}
关于android - 将异步方法的结果保存在 Kotlin 中的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64491035/