android - 将异步方法的结果保存在 Kotlin 中的变量中

标签 android kotlin asynchronous

我尝试将异步 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/

相关文章:

android - 如何在Activity中的RecyclerView适配器声明中声明Click监听器

Android Studio 汽车 API

java - 将多个 xml 对象传递给 jax-rs 服务

android - 试驾安卓

java - slf4j简单,是否可以过滤同一级别内的消息?

javascript - react.js - 处于异步数据状态的深层对象不起作用

Android Activity Transition 幻灯片动画

android - 如何使用 Dagger 柄向网络模块添加 retrofit 基本身份验证?

asynchronous - 这个异步 HystrixCommand 有什么问题?

asynchronous - 如何使用 ansible 中的包含来并行化循环