Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle status of a network request with LiveData, ViewModel and update UI accordingly

Tags:

android

mvvm

Using Retrofit I am able to get the list of users but in case of errors, how should I manage to send notifications to UI.

I am using Android architecture components 'ViewModel', 'LiveData' in MVVM pattern and Retrofit as network library.

like image 268
Sharad Avatar asked Jan 28 '18 02:01

Sharad


People also ask

How do I use livedata in a ViewModel?

Create LiveData objects in the ViewModel and use them to expose state to the UI layer. Activities and fragments should not hold LiveData instances because their role is to display data, not hold state. Also, keeping activities and fragments free from holding data makes it easier to write unit tests.

What is livedata in Android?

To understand that, you should be good with the basics. In simple terms, LiveData is an observable data holder class. This means it can hold a set of data that can be observed from other Android components like Activities, Fragments, and Services. It’s lifecycle-aware and mostly used to update UI from the ViewModel in MVVM architecture projects.

Can livedata handle asynchronous streams of data?

It may be tempting to work LiveData objects in your data layer class, but LiveData is not designed to handle asynchronous streams of data.

What happens when livedata is updated?

When you update the value stored in the LiveData object, it triggers all registered observers as long as the attached LifecycleOwner is in the active state. LiveData allows UI controller observers to subscribe to updates.


1 Answers

Finally I found the answer for my question. Official document itself provides answer for this. Use Resource along with NetworkBoundResource to achieve this.

Direct link: https://developer.android.com/topic/libraries/architecture/guide.html#addendum

like image 96
Sharad Avatar answered Sep 18 '22 20:09

Sharad