Ad
How To Convert Row JSON Response Into LiveData Without Using Room?
I am stuck at the conversion of JSON response into LiveData. This can be possible using Room. But I am not using Room in my app.
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
)
)
}
}
})
}
Ad
Answer
I have converted the server's response into MutableLiveData as below in code:
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
)
)
}
}
})
}
Ad
source: stackoverflow.com
Related Questions
- → should I choose reactjs+f7 or f7+vue.js?
- → Phonegap Android write to sd card
- → Local reference jquery script in nanohttpd (Android)
- → Click to navigate on mobile devices
- → How to allow api access to android or ios app only(laravel)?
- → Access the Camera and CameraRoll on Android using React Native?
- → React native change listening port
- → What is the default unit of style in React Native?
- → Google play market autocomplete icon
- → Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`
- → Using Laravel with Genymotion
- → react native using like web-based ajax function
- → react native pdf View
Ad