Search code examples
androidandroid-architecture-componentsandroid-livedata

Android Architecture Components LiveData progress update


I am not sure if I am missing something. I cannot seem to find any samples or tutorials about how to go about publishing progress while pulling data with LiveData.

For example; say I have 5000 records in my db and want to show which record I am reading from the database instead of showing an intermediate progress bar.

Samples show how to load data from a db or network and return a List. However, there is no mention of how one publish the progress like on AsyncTask.

As far as I understand you get all data with:

ViewModelProviders.of(this).get(MyViewModel.class);
model.getData().observe(this, data -> {
  // update UI
});

I guess one could create some sort of listener/callback but shouldn't Architecture Components save you from this? Am I missing something?


Solution

  • The Guide to App Architecture shows an example of how to expose network status. I guess you can modify the following generic class by adding your progress percentage while loading.

    //a generic class that describes a data with a status
    public class Resource<T> {
        @NonNull public final Status status;
        @Nullable public final T data;
        @Nullable public final String message;
        private Resource(@NonNull Status status, @Nullable T data, @Nullable String message) {
            this.status = status;
            this.data = data;
            this.message = message;
        }
    
        public static <T> Resource<T> success(@NonNull T data) {
            return new Resource<>(SUCCESS, data, null);
        }
    
        public static <T> Resource<T> error(String msg, @Nullable T data) {
            return new Resource<>(ERROR, data, msg);
        }
    
        public static <T> Resource<T> loading(@Nullable T data) {
            return new Resource<>(LOADING, data, null);
        }
    }
    

    Also, you can check a full implementation here.