密封 class 的协程

Coroutines with sealed class

我的项目有很多操作必须一个接一个地执行。我正在使用侦听器,但我发现了这个教程 Kotlin coroutines on Android,我想用更易读的代码更改我的服务器调用。但我想我错过了一些东西。下面的代码总是 return 来自 getTime1() 函数的错误:

suspend fun getTimeFromServer1() :ResultServer<Long> {
        val userId = SharedPrefsHelper.getClientId()
        return withContext(Dispatchers.IO) {
            val call: Call<ResponseFromServer>? = userId?.let { apiInterface.getTime(it) }
            (call?.execute()?.body())?.run {
                val time:Long? = this.data?.time
                time?.let {
                    Timber.tag("xxx").e("time received it ${it}")// I am getting the right result here
                    ResultServer.Success(it)
                }
                Timber.tag("xxx").e("time received ${time}")
            }
            ResultServer.Error(Exception("Cannot get time"))
        }
    }


fun getTime1() {
        GlobalScope.launch {
            when (val expr: ResultServer<Long> = NetworkLayer.getTimeFromServer1()) {
                is ResultServer.Success<Long> -> Timber.tag("xxx").e("time is ${expr.data}")
                is ResultServer.Error -> Timber.tag("xxx").e("time Error") //I am always get here
            }}
    }
    }

但是如果我使用侦听器 (getTime()) 一切正常:

 suspend fun getTimeFromServer(savingFinishedListener: SavingFinishedListener<Long>) {
        val userId = SharedPrefsHelper.getClientId()
        withContext(Dispatchers.IO) {
            val call: Call<ResponseFromServer>? = userId?.let { apiInterface.getTime(it) }
            (call?.execute()?.body())?.run {
                val time:Long? = this.data?.time
                time?.let {
                    Timber.tag("xxx").e("time received it ${it}")
                    savingFinishedListener.onSuccess(it)
                }

            }
            savingFinishedListener.onSuccess(null)
        }
    }

   fun getTime() {
        GlobalScope.launch {
            NetworkLayer.getTimeFromServer(object:SavingFinishedListener<Long>{
                override fun onSuccess(t: Long?) {
                    t?.let {
                        Timber.tag("xxx").e("time here $it") //I am getting the right result
                    }
                }
            })
           }
        }

在此先感谢您的帮助。

lambda 的最后一行隐式是该 lambda 的 return 值。由于您的 withContext lambda 中没有任何明确的 return 语句,因此它的最后一行:

ResultServer.Error(Exception("Cannot get time"))

意味着它总是return这个错误。您可以将 return@withContext 放在 ResultServer.Success(it) 之前,以使该行代码也来自 lambda return。

旁注:don't use GlobalScope.