【问题标题】:Save result of async method in variable in Kotlin将异步方法的结果保存在 Kotlin 的变量中
【发布时间】:2020-10-22 21:52:38
【问题描述】:

我尝试将异步 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 上发现了一个类似的问题,但它并没有帮助我。

有人可以帮助我吗?!

【问题讨论】:

  • 也许this 就是您要找的东西?

标签: android kotlin asynchronous


【解决方案1】:

你在这里做什么(在 lambda 中保存值)在技术上是正确的,但在功能上 - 不一定:值在 lambda 更新之前使用。

考虑从回调 lambda 开始进一步的逻辑,您会在其中收到 result

请参阅下面的 sn-p 以获得更好的概述:

        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) {
            // ...
        }
    }

【讨论】:

  • 我不太确定我是否得到了你,但我应该在我收到结果的 lamda 中调用 android 的 onCreate() 方法?
  • 绝对不是!您不应该真正自己调用任何活动生命周期方法。我考虑过提取您在异步调用下方的逻辑(以 if (isAuthenticated == true) { 行开头的单独方法,该方法将接受您在 lambda 中收到的参数。请参阅编辑后的答案。
【解决方案2】:

我不确定这是否是最佳做法,但在涉及异步函数时,它在代码可读性和功能方面对我有用。
假设你有一个异步函数doSomethingAsync。如果我需要在执行其他指令(例如您的 if 语句)之前完成它,我会将 1 个或多个函数传递给 async 函数,每个函数都涵盖特定场景。
我的意思是:

    fun doSomethingAsync() (
        onSuccess : (fetchedObject : Any) -> Unit,   // Do stuff with returned value
        onFailure : (e : Exception) -> Unit,  // Catch an exception
        onComplete : () -> Unit  // Do stuff after the value has been fetched
    ) {
        // Your async function body, which could return a Task
        .addOnSuccessListener { result ->
            onSuccess(result)
            onComplete()
    }
        .addOnFailureListener { exception -> 
            onFailure(exception)
    }
}

在您的情况下,您可以将 if 语句和后面的内容放入一个函数中,您可以将其作为函数参数传递给异步函数,以便在异步任务完成后调用。

        Amplify.Auth.fetchAuthSession(onComplete : () -> Unit)
        {result ->
            Log.i(TAG, "Amplify: Fetch Auth Session $result")
            isAuthenticated = result.isSignedIn
            onComplete()
        },
        {error ->
            Log.e(TAG , "Amplify: Fetch Auth Session $error")
        }
    )
    
    fun onComplete() {
         // Assume that ifAuthenticated == true, and call this after 
         // you get the Auth results.
    }

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    相关资源
    最近更新 更多