0

I have a use case where I have to convert a button press to database fetch. I have an Observable from the button press. I am doing a flatMap of the observable to another observable which fetches items from the DB.

Observable<Customer> customerListObservable = getButtonPressObservable()
        .map(event -> new Object())
        .startWith(new Object())
        .flatMap(event -> DatabaseHelper.getDatabase()
                .select("select * from Customer")
                .autoMap(Customer.class)
                .toObservable());

However before button being pressed, I would need to fetch items from db for the first time. Again, on subsequent button presses, fetches should happen again.

Is there any other clean way other than the above code to generate initial value?

prem
  • 81
  • 1
  • 6

1 Answers1

0

I would concat the observables:

Observable<Customer> customerObservable = Observable.concat(getFromDb(), getAfterClick());

private Observable<Customer> getFromDb() {
   return DatabaseHelper.getDatabase()
                .select("select * from Customer")
                .autoMap(Customer.class)
                .toObservable());
}

private Observable<Customer> getAfterClick() {
   return getButtonPressObservable()
        .map(event -> new Object())
        .startWith(new Object())
        .flatMap(event -> getFromDb());
}
Tatu Lahtela
  • 4,514
  • 30
  • 29