I need a data , i firstly query it from database ,if the database did not contain the data, than i get the data from network and store it in database.
I use room and RxJava to do this
Here is the google code to create a flowable in RxRoom.java:
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public static <T> Flowable<T> createFlowable(final RoomDatabase database,
final String[] tableNames, final Callable<T> callable) {
return createFlowable(database, tableNames).observeOn(sAppToolkitIOScheduler)
.map(new Function<Object, Optional<T>>() {
@Override
public Optional<T> apply(@NonNull Object o) throws Exception {
T data = callable.call();
return new Optional<>(data);
}
}).filter(new Predicate<Optional<T>>() {
@Override
public boolean test(@NonNull Optional<T> optional) throws Exception {
return optional.mValue != null;
}
}).map(new Function<Optional<T>, T>() {
@Override
public T apply(@NonNull Optional<T> optional) throws Exception {
return optional.mValue;
}
});
}
So if a sql query results nothing,the flowable will filter the original data.
But sometime we need the original result
How can i do it?
I have the same problem with you! Sometime when I open an new view, then I emit a request to load data, anyway I hope there is a result can be returned to view so that I can change it, but because the null data is filtered, I will never get a response in view if database doesn't have any data and first network request is failed, It's unbearable!
You can return a Flowable<List<T>> instead of Flowable<T>.
If there are no rows in the table to be returned by your query, then the Flowable will emit an empty list.
@florina-muntenescu Thanks, got it!
thank you!
@florina-muntenescu I have this query:
@Query("SELECT SUM(count*amount) FROM basket_items")
Flowable<Long> totalSum();
How can I return List
Most helpful comment
You can return a
Flowable<List<T>>instead ofFlowable<T>.If there are no rows in the table to be returned by your query, then the
Flowablewill emit an empty list.