Getting started with RxJava with sqlite

前端 未结 1 1591
一向
一向 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<String, String> getDataFromDatabase() { 
       Map<String, String> result = new HashMap<>(); 
       // do whatever you need to (i.e. db query, cursor) to fill it in 
       return result; 
    } 
    
    private Callable<Map<String, String>> getData() { 
       return new Callable() { 
          public Map<String, String> call() { 
            return getDataFromDatabase(); 
        } 
    }
    
    // in utility class  RxUtil.java 
    public static <T> Observable<T> makeObservable(final Callable<T> func) {
            return Observable.create(
                    new Observable.OnSubscribe<T>() {
                        @Override
                        public void call(Subscriber<? super T> 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<Map<String, String>> getDataObservable() {
       return RxUtil.makeObservable(getData());
    }
    
    0 讨论(0)
提交回复
热议问题