Getting started with RxJava with sqlite

前端 未结 1 1596
一向
一向 2021-02-06 09:57

I\'m in the process of learning RxJava and have went thru several articles and videos. I totally felt awesome of what RxJava can offer, so I think currently getting the sense of

1条回答
  •  时光取名叫无心
    2021-02-06 10:53

    I'm sure that there are going to be a bunch of other opinions, but so far, I've taken a couple of different approaches:

    • If you want a relatively small amount of data (and you can guarantee that it will always have a known upper bound on size), then:

      • create a synchronous method that accesses the database, gets a cursor, iterates the cursor to create a data structure (e.g. a List) containing the data, and then returns it.
      • Create a Callable that invokes the method
      • Use rx.fromCallable to create an an Observable
    • If you need an unbounded number of rows, do something similar to the above, but return the Cursor.

    EDIT: sample code:

    private Map getDataFromDatabase() { 
       Map result = new HashMap<>(); 
       // do whatever you need to (i.e. db query, cursor) to fill it in 
       return result; 
    } 
    
    private Callable> getData() { 
       return new Callable() { 
          public Map call() { 
            return getDataFromDatabase(); 
        } 
    }
    
    // in utility class  RxUtil.java 
    public static  Observable makeObservable(final Callable func) {
            return Observable.create(
                    new Observable.OnSubscribe() {
                        @Override
                        public void call(Subscriber subscriber) {
                            try {
                                T observed = func.call();
                                if (observed != null) { // to make defaultIfEmpty work
                                    subscriber.onNext(observed);
                                }
                                subscriber.onCompleted();
                            } catch (Exception ex) {
                                subscriber.onError(ex);
                            }
                        }
                    });
        }
    
    
    // and finally, 
    public Observable> getDataObservable() {
       return RxUtil.makeObservable(getData());
    }
    

    0 讨论(0)
提交回复
热议问题