【问题标题】:How can i return the value retrieved from retrofit?如何返回从改造中检索到的值?
【发布时间】:2023-03-18 10:15:01
【问题描述】:

我想返回从改造 API 入队调用返回的值。我的函数返回 null,因为 enqueue 是异步的,它在我的函数返回 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
}

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

【问题讨论】:

  • 可以使用实时数据/协程/接口回调来实现。
  • 您可以接受 lambda 作为函数的参数并在 onResponse() 中调用它或使用协程从函数异步返回示例:suspendCoroutine
  • 我尝试过使用实时数据,但它没有用,因为这个函数在我的存储库中,我正试图从我的 ViewModel 中调用它。
  • 如何使用接口回调?

标签: android kotlin asynchronous return retrofit


【解决方案1】:

制作一个界面。像这样:

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 方法代替回调

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 2018-06-13
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多