0

So I have Room database and I'm using MutableLiveData to load four lists from database in one screen each of these four lists have separate callbacks which are called when data is loaded and I have progress bar which I show when data starts loading and I want to hide this progress bar when all four lists are loaded, but the problem is that callbacks can be triggered at random times just because of all sorts of delays so whats my options to figure out when all lists are loaded?

LeTadas
  • 3,436
  • 9
  • 33
  • 65

1 Answers1

2

Room supports RxJava. You can return RxJava streams and combine your streams with rich RxJava operators. Check the list of available in RxJava Wiki.

Here is untested exmple to give you idea of what am talking about

@Dao
public interface TodoDao {
    @Query("SELECT * FROM TodoList")
    public Observable<List<ToDoEntity>> getAllTodos();
}


@Dao
public interface AnotherListDao {
    @Query("SELECT * FROM AnotherList")
    public Observable<List<ToDoEntity>> getAllOtherList();
}


MyDatabase db = ...//get database instance here

//most of the times d is member class that is disposed before object of that class goes out of scope
Disposable d = Observable.merge(db.getAllTodos(), db.getAllOtherList())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(subscription -> {
                    subscription.request(Long.MAX_VALUE);

                    //data is loading
                })
                .subscribe(data -> {
                            //onNext
                            //work with data here
                        },
                        error -> {
                            //onError
                            //an erro happened here, service it
                        },
                        () -> {
                            //onComplete
                            //task is done
                        }
                );

//to avoid leaking the Observable dispose it in relevant lifecycle
if(d && d.isDisposable())
    d.dispose())

Let me know if there is anything that is not clear.

Stefano Mtangoo
  • 6,017
  • 6
  • 47
  • 93