首页 > 解决方案 > 如何返回从改造中检索到的值?

问题描述

我想返回从改造 API 入队调用返回的值。我的函数返回 null,因为队列是异步的,它在我的函数返回 null 后执行。

fun login(context: Context, username: String, password: String): UserModel {
    var userModel = UserModel()

    RetrofitClient.AUTH = Prefs.getInstance(context).auth
    Log.e("TAG", "Login Auth: " + RetrofitClient.AUTH)
    RetrofitClient.instance.userLogin(username, password)
        .enqueue(object : Callback<LoginModel> {
            override fun onResponse(call: Call<LoginModel>, response: Response<LoginModel>) {
                Log.e("TAG", "Login Response: " + response.message())
                Log.e("TAG", "Login Response: " + response.body().toString())
                userModel = response!!.body()!!.data.user
                Log.e("TAG", "Login User Model Mutable Live Data: " + userModel.full_name)
            }
            override fun onFailure(call: Call<LoginModel>, t: Throwable) {
                Toast.makeText(context, t.message, Toast.LENGTH_LONG).show()
            }
        })

    Log.e("TAG", "Return Login: " + userModel.full_name)
    return userModel
}

enqueue 函数内的日志返回我需要的准确值。但是上面的日志返回返回null。

标签: androidkotlinasynchronousreturnretrofit

解决方案


制作一个界面。像这样:

interface ApiResult{
 void success(UserModel userModel);
 void error(Throwable t);
}

然后将此接口的一个实例作为参数传递给您的登录方法:

fun login(context: Context, username: String, password: String,result : ApiResult) {
    var userModel = UserModel()
    RetrofitClient.AUTH = Prefs.getInstance(context).auth
    Log.e("TAG", "Login Auth: " + RetrofitClient.AUTH)
    RetrofitClient.instance.userLogin(username, password)
        .enqueue(object : Callback<LoginModel> {
            override fun onResponse(call: Call<LoginModel>, response: Response<LoginModel>) {
                Log.e("TAG", "Login Response: " + response.message())
                Log.e("TAG", "Login Response: " + response.body().toString())
                userModel = response!!.body()!!.data.user
                Log.e("TAG", "Login User Model Mutable Live Data: " + userModel.full_name)
                result.success(userModel);
            }
            override fun onFailure(call: Call<LoginModel>, t: Throwable) {
                Toast.makeText(context, t.message, Toast.LENGTH_LONG).show()
                result.error(t);
            }
        })
}

这是一个使用回调获取 API 结果的简单示例。您还可以使用 lambda 方法而不是回调


推荐阅读