android - 如何返回从改造中检索到的值?
问题描述
我想返回从改造 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。
解决方案
制作一个界面。像这样:
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 方法而不是回调
推荐阅读
- java - 使用 Apache POI 3.17 在 java 中写入文件时文件损坏
- laravel - Laravel Eloquent 与分组和排序有很多关系
- spring - 使用 Spring Data MongoDB ReactiveMongoRepository 进行切片投影?
- html - Bootstrap 中的等高网格,带有 Flexbox 的多维图像
- ruby-on-rails - Heroku 在迁移期间挂起并出现奇怪的 pg_advisory_unlock
- json - SyntaxError:JSON.parse 中位置 1 的 JSON 中的意外标记 <
) - php - Symfony __construct 用法
- coldfusion - Coldfusion 2016 使用 cfscript mail() 时如何包含模板?
- c# - 如何使此 MenuItem 中的复选标记尊重整体前景色?
- android - 在活动之间传递数据到 asyncTask 和从 asyncTask 到活动