mercredi 29 juin 2016

RxAndroid: Observable.first() returns List of null objects

Following this tutorial I've created two sources for fetching data. I expect that if there is no data locally I'll sent network request. But all the time get list of null objects from local source (which is first in Observable.concat).

For local source using SQLite with SQLBrite wrapper and Retrofit for remote source:

@Override
public Observable<Item> get(String id) {
    //creating sql query

    return databaseHelper.createQuery(ItemEntry.TABLE_NAME, sqlQuery, id)
        .mapToOneOrDefault(mapperFunction, null);
}

There is method in repository for concating observables:

@Override
public Observable<Item> get(String id) {
    Observable<Item> local = localDataSource
        .get(id)
        .doOnNext(new Action1<Item>() {
            @Override
            public void call(final Item item) {
                // put item to cache
            }
        });
    Observable<Item> remote = remoteDataSource
        .get(id)
        .doOnNext(new Action1<Item>() {
            @Override
            public void call(final Item item) {
                // save item to database and put to cache
            }
        });
    return Observable.concat(local, remote).first();
}

For getting it with list of ids I'm using next method:

@Override
public Observable<List<Item>> getList(final List<String> ids) {
    return Observable
        .from(ids)
        .flatMap(new Func1<String, Observable<Item>>() {
            @Override
            public Observable<Item> call(String id) {
                return get(id);
            }
        }).toList();
}

And subscription in fragment:

Subscription subscription = repository
    .getList(ids)
    .flatMap(new Func1<List<Item>, Observable<Item>>() {
        @Override
        public Observable<Item> call(List<Item> result) {
            return Observable.from(result);
        }
    })
    .toList()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Observer<List<Item>>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onNext(List<Item> result) {
            // there get list of null objects
        }
}); 

So, main goal is first check local storage and if there is no item - make request to server. But now if item isn't exist I get null instead of send request.

Could someone help me understand why?

Aucun commentaire:

Enregistrer un commentaire