【问题标题】:Returns null getrequest retrofit kotlin返回 null getrequest 改造 kotlin
【发布时间】:2021-05-27 01:37:37
【问题描述】:

我的viewmodel 中有此功能,我想通过获取请求检索位置列表。 但是当我从片段中调用函数fetchAllLocations 时,该函数返回null。但在onResponse 方法中,列表位置不为空。我不知道为什么位置在onResponse 方法之外为空。

      fun fetchAllLocations(): List<Location>?
            {
        
                val call = apiInterface?.fetchAllLocation()
                var locations: List<Location>?  = null
        
                call?.enqueue(object : Callback<List<Location>> {
        
                    override fun onResponse(call: Call<List<Location>>, response: Response<List<Location>>) {
                        locations = response.body()
        
        
        
                    }
        
                    override fun onFailure(call: Call<List<Location>>, t: Throwable) {
                        
                    }
                })
                return locations
            }
        }

【问题讨论】:

  • 因为是异步进程
  • 这是由于异步行为。 call?.enqueue 是一个异步操作。因此,当此 API 调用时,它会返回响应回调下的位置列表。由于您要返回位置,因此 fetchAllLocations 将始终返回空位置。
  • 那我应该如何检索数据?
  • 您可以在 ViewModel 中使用实时数据并从片段中观察此实时数据,而不是返回。在 onResponse 回调中,在 livedata 中发布值
  • 你有一个例子我怎么能做到这一点?

标签: android kotlin retrofit get-request


【解决方案1】:

在您的视图模型中添加此实时数据

   val locationLiveData by lazy { MutableLiveData<<List<Location>>() }
        
    fun fetchAllLocations(){
            
                    val call = apiInterface?.fetchAllLocation()
                    call?.enqueue(object : Callback<List<Location>> {
            
                        override fun onResponse(call: Call<List<Location>>, response: Response<List<Location>>) {
                            locations = response.body()
                            locationLiveData.postValue(locations)
                        }
            
                        override fun onFailure(call: Call<List<Location>>, t: Throwable) {}
                    })
                }
   }

从您的片段类中观察此实时数据。

viewModel.locationLiveData.observe(viewLifecycleOwner, Observer {
            //here you will get list
        })

参考项目:https://github.com/droiddevgeeks/MovieSearch (Java) https://github.com/droiddevgeeks/TrendingRepo(科特林)

【讨论】:

    【解决方案2】:

    Retrofit 运行异步进程,因此您实际上返回列表的初始值为 null ,因此您需要使用 LiveData ,它是 Android Jetpack 的一部分,它使用类 Observer 类来观察数据的变化,您可以在您的案例中注册一个观察者并观察其值的变化,当这种情况发生时,您可以实际使用该数据。 更多信息可以查看官方docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2018-01-22
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多