【问题标题】:Unable to get response with Retrofit Coroutine api call无法通过 Retrofit Coroutine api 调用获得响应
【发布时间】:2020-01-09 08:01:51
【问题描述】:

我正在尝试从 api 获取对实时数据的响应,但未使用此代码调用请求。

class AuthActivityViewModel : ViewModel() {

    var authResp: LiveData<ObjAuthResp> = MutableLiveData()

    val repository = BaseRepository()

    fun login(username: String, password: String) {
        authResp = liveData(Dispatchers.IO) {
          val resp = repository.login(username, password)
            emit(resp)
        }
    }
}

但它适用于此代码。

class AuthActivityViewModel : ViewModel() {

    val repository = BaseRepository()

    var authResp = liveData(Dispatchers.IO) {
        val resp = repository.login(username, password)
            emit(resp)
    }    

}

API 服务

@POST("profile/pub/auth/login")
suspend fun login(@Body authReqBody : ObjAuthReqBody): ObjAuthResp

基础存储库

open class BaseRepository {

    suspend fun login(username:String,password:String) = service.login(ObjAuthReqBody( username, password))   
} 

从活动中调用

   btn_login.setOnClickListener {
    viewModel.login(edt_username.text.toString(), 
    edt_password.text.toString())
    }

【问题讨论】:

  • 向我们展示您的存储库代码
  • 我认为这是因为您没有从任何地方调用 ViewModel 中的登录功能
  • 相信我,我正在打电话)
  • 你有什么证据证明它没有被调用?你有一些日志语句吗?例如,将一条日志语句放入单击侦听器中,然后将一条日志语句放入login 函数中,然后发布该代码。
  • 感谢您花时间在这个案例上,但我确实在将问题发布到此处之前调试了我的代码,并且调试器到达了 authResp = liveData(Dispatchers.IO) {... 但改造确实不调用 api,我已将 HttpLoggingInterceptor 附加到我的 Retrofit,否则我会从中获取调用日志,我在案例 1 中这样做了,它在没有登录功能的情况下工作

标签: android retrofit2 android-livedata kotlin-coroutines


【解决方案1】:

回答我自己的问题,

问题出在authResp = liveData(Dispatchers.IO) {... 行中,这是在创建新的 LiveData 而旧的观察者在观察初始的var authResp: LiveData&lt;ObjAuthResp&gt; = MutableLiveData()。因此,由于没有观察者监听新创建的LiveData,因此甚至没有进行调用。

此代码正在运行

  var authResp = MutableLiveData<ObjAuthResp>()

 fun login(username: String, password: String) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val resp = repository.login(username, password)
                authResp.postValue( resp)

            }
        }
    }

【讨论】:

    猜你喜欢
    • 2016-03-18
    • 2021-11-15
    • 2021-10-19
    • 2019-04-27
    • 1970-01-01
    • 2020-08-25
    • 2022-11-23
    • 2021-11-23
    相关资源
    最近更新 更多