如何在不使用Room的情况下将行JSON响应转换为LiveData?

时间:2019-05-10 09:48:21

标签: android android-room android-livedata android-mvvm

我一直坚持将JSON响应转换为LiveData。使用Room可以做到这一点。但是我没有在应用程序中使用Room。

private fun fetchFromNetwork(dbSource: LiveData<T>) {
    //here 'result' is MediatorLiveData
    result.addSource(dbSource) { newData -> result.setValue(Resource.loading(newData)) }
     createCall().enqueue(object : Callback<V> {
         override fun onResponse(call: Call<V>, response: Response<V>) {
             result.removeSource(dbSource)

          //   response.body() is JSON response from server and need tobe convert into LiveData type

             result.addSource(convertedLiveData) { newData ->
                 if (null != newData)
                     result.value = Resource.success(newData)
             }
         }

         override fun onFailure(call: Call<V>, t: Throwable) {
             result.removeSource(dbSource)
             result.addSource(dbSource) { newData ->
                 result.setValue(
                     Resource.error(
                         getCustomErrorMessage(t),
                         newData
                     )
                 )
             }
         }
     })
 }

1 个答案:

答案 0 :(得分:0)

我已将服务器的响应转换为 MutableLiveData ,如下代码所示:

private fun fetchFromNetwork(dbSource: LiveData<T>) {
     result.addSource(dbSource) { newData -> result.setValue(Resource.loading(newData)) }
     createCall().enqueue(object : Callback<V> {
         override fun onResponse(call: Call<V>, response: Response<V>) {
             result.removeSource(dbSource)
            // here converting server response in to MutableLiveData
             val converted: MutableLiveData<T> = MutableLiveData()
             converted.value = response.body() as T
             result.addSource(converted) { newData ->
                 if (null != newData)
                     result.value = Resource.success(newData)
             }
         }

         override fun onFailure(call: Call<V>, t: Throwable) {
             result.removeSource(dbSource)
             result.addSource(dbSource) { newData ->
                 result.setValue(
                     Resource.error(
                         getCustomErrorMessage(t),
                         newData
                     )
                 )
             }
         }
     })
 }