【发布时间】: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