I am using Room for the database layer in my application and Retrofit for network calls - both in room and retrofit I am using RxJava2 (this is my first project with rxjava so I am still quite newbie in this area). To inject database, api etc. I am using Dagger 2.
I want to make a Network Call and add response from the network to the database. When there is no need for making another network call - I want to fetch data from the database. I am having problem with the use of Maybe / Flowable in my room repository.
This is Dao:
#Dao
public interface CoinDao {
#Query("SELECT * FROM coin")
Flowable<List<Coin>> getAllCoins();
#Insert
void insert(List<Coin> coins);
#Update
void update(Coin... coins);
#Delete
void delete(Coin... coins);
}
This is my repository:
public class CoinRepository implements Repository {
private CoinMarketCapNetworkApi api;
private final CoinDao coinDao;
public CoinRepository(CoinMarketCapNetworkApi api, CoinDao coinDao) {
System.out.println("Creating CoinRepository");
this.api = api;
this.coinDao = coinDao;
}
#Override
public Flowable<List<Coin>> getCoinResults() {
System.out.println("getting coin results");
return getCoinResultsFromDatabase().switchIfEmpty(getCoinResultsFromNetwork())
}
#Override
public Flowable<List<Coin>> getCoinResultsFromNetwork() {
System.out.println("getting results from network");
return api.getCoins().doOnNext(new Consumer<List<Coin>>() {
#Override
public void accept(List<Coin> coins) throws Exception {
System.out.println("inserting to db");
coinDao.insert(coins);
}
});
}
#Override
public Flowable<List<Coin>> getCoinResultsFromDatabase() {
System.out.println("getting coins from database");
return coinDao.getAllCoins();
}
}
I firstly run the app to fill the database only with network call
#Override
public Flowable<List<Coin>> getCoinResults() {
return getCoinResultsFromNetwork();
}
And when the network call was executed the data was successfuly added to the database - I run the app once again with only getting data from database and it was also successfull - the data was fetched from db.
#Override
public Flowable<List<Coin>> getCoinResults() {
return getCoinResultsFromDatabase();
}
However when I try now to do such a thing
return getCoinResultsFromDatabase.switchIfEmpty(getCoinResultsFromMemory));
The problem is that everytime switchIfEmpty is executed and every time "getCoinResultsFromMemory()" is executed (even though the data in database is available).
According to https://medium.com/google-developers/room-rxjava-acb0cd4f3757
I have read that the Flowable when there is no data in database will emit nothing and I should use Maybe. But why getResultsFromMemory() returns empty even though there is data in database? How exactly should I use Maybe in this scenario?
I have tried changing Flowable to Maybe
Maybe<List<Coin>> getCoinResultsFromDatabase()
and doing something like this - to access the resutl from maybe and check there if the list is empty or not, but I don't know how to return flowable in this case:
public Flowable<List<Coin>> getCoinResults() {
getCoinResultsFromDatabase().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<Coin>>() {
#Override
public void accept(List<Coin> coins) throws Exception {
System.out.println("returning coins from maybe" + coins.get(0).getId());
if (coins.isEmpty()) {
System.out.println("coin list is empty");
Flowable<List<Coin>> flowable = getCoinResultsFromNetwork();
} else {
Flowable<List<Coin>> flowable = getCoinResultsFromDatabase();
}
}
});
return flowable //how to access this flowable??
}
Maybe I am missing something and there is a better and more clean solution.
There are few issues with your code:
1.Looks like in room Flowable<List<Coin>> getAllCoins() will always return some value: either list of items or empty list so Maybe will not help here
2.In this piece of code
#Override
public Flowable<List<Coin>> getCoinResults() {
System.out.println("getting coin results");
return getCoinResultsFromDatabase().switchIfEmpty(getCoinResultsFromNetwork())
}
the getCoinResultsFromNetwork is called right when you call getCoinResults method not when the flowable is empty (this is plain java method call)
You need to perform deferred call. The final solution may look like this
#Override
public Flowable<List<Coin>> getCoinResults() {
System.out.println("getting coin results");
return getCoinResultsFromDatabase()
.filter(list -> !list.isEmpty())
.switchIfEmpty(
Flowable.defer(() -> getCoinResultsFromNetwork()))
}
Related
I'm using LiveData with MVVM. After updating my database with Room, I am trying to sendback both the Object I inserted into my Room database, and also the adapter position. In my ViewModel class, the method is:
private MutableLiveData<String> insertItemLiveData = new MutableLiveData<>;
public void insertMenuItem(MenuItem menuItem, int adapterPositionToUpdate){
repo.insertOrder(menuItem.getId())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Integer>() {
#Override
public void onSubscribe(#NonNull Disposable d) {
}
#Override
public void onSuccess(#NonNull Integer integer) {
//The order is successfully inserted into database
//So I return back the name of the inserted order
String s = "Inserted Item: " + menuItem.getNameOfOrder();
insertItemLiveData.setValue(s);
}
#Override
public void onError(#NonNull Throwable e) {
errorLiveData.setValue("Failed to cancel order.");
}
});
}
In the on success method, it returns the String I want to display, but I also want to update the position of the Recyclerview item that has changed. What is the best way to handle this situation?
I can use a wrapper class and have setters for a String and the adapter position, but I feel like there's probably a better way to do this.
A resource wrapper is a good idea for it.MVVM Resource Wrapper With Live Data you can check my code to get an insight on how to use it
I am unable to get a LiveData ArrayList from a Room database but I am able to retrieve a standard ArrayList and cannot figure out why.
I have run this code in debug mode and the ArrayList returns a size of 4, which it should. The LiveData ArrayList, when get value is used returns null. I have run the LiveData query both within an executor and outside of the executor and it returns null.
Declarations
public LiveData<List<CourseEntity>> courseEntities;
private List<CourseEntity> courseData = new ArrayList<>();
Code outside of executor
public void loadData(final int termId) {
courseEntities = courseRepository.getCourseByTermId(termId);
courseData = courseEntities.getValue();
}
Code inside executor
public void loadData(final int termId) {
executor.execute(new Runnable() {
#Override
public void run() {
courseEntities = courseRepository.getCourseByTermId(termId);
courseData = courseEntities.getValue();
}
});
}
Code using just an ArrayList
public void loadData(final int termId) {
executor.execute(new Runnable() {
#Override
public void run() {
courseData = courseRepository.getCourseByTerm(termId);
}
});
}
Queries from Dao
#Query("SELECT * FROM course " +
"WHERE term_id = :termIdSelected ORDER BY course_start" )
LiveData<List<CourseEntity>> getCourseByTermId(int termIdSelected);
#Query("SELECT * FROM course WHERE term_id = :termIdSelected ORDER BY course_start")
List<CourseEntity> getCourseByTerm(int termIdSelected);
This produces a null value for the LiveData instead of a value of 4 like the plain ArrayList produces. The only difference being the LiveData wrapper for the result. Any wisdom someone can share would be most appreciated.
When you have a Room #Dao return a LiveData (or an RxJava type like Observable or Single), the generated implementation will do the actual work on a background thread. So, when getCourseByTermId() returns, the work will not yet have begun, so the LiveData will not have results yet.
Reactive types, like LiveData, are meant to be observed. So, your activity/fragment/whatever would observe() the LiveData and react to the result when it is delivered.
I am very new to RxJava and I'm working on an Android app with it. I am making a network request and I'd like my Fragment to update the UI based on the network returned data, and I'm looking for a good 'rx' way to do this. Basically I have my Fragment immediately firing to my viewmodel that it should make the server call. I need to make the server call and notify/send that data to the viewModel so that I can update it to the fragment. Normally (without rx), I'd just pass all of this data with variables, but how can I achieve this data flow using rx and observables?
Thanks everyone.
Create a separate Repository layer, access it only from your viewModels.
In this way you will have view/databinding triggering requests.
Next, have some State management inside Repository or store some data there(use LiveData)
In your ViewModel assign value to the ref of LiveData from repository. So anytime you update it inside Repository - viewModel will have the same object.
Finally, you can observe that viewModel's LiveData.
val someData = MutableLiveData<SomeObject>() - this one inside repository, now you will be able to save any network call result inside repository.
Have your ViewModel contain next one: val someData= Repository.instance.someData
And from fragment/activity use : viewModel.someData.observe(this, {...})
Going to show simple example with code. Another way of doing this using concept single source of truth (SSOT).
Activity-->ViewModel--->Repository--->Insert On Room DB
Step 01: Get all data from room database with Live Data query. And set adapter.
Step 02: Call from Activity/Fragment to remote database/repository to get data.
Step 03: After getting data from remote repository insert it to room database.
Step 04: You have already observing data with Live Query on step 01 so as soon as you
insert data on room database your live observe query will fire again and update
your listview.
Now following example is not complete. But to get a rough idea.
To call & update List using LiveData.
Activity/ Fragment:
RouteViewModel mViewModel = ViewModelProviders.of(this).get(RouteViewModel.class);
mViewModel.getAllRoutes().observe(this, new Observer<List<Route>>() {
#Override
public void onChanged(#Nullable final List<Route> items) {
// will call automatic as soon as room database update
adapter.setItems(items);
}
});
//init/write a remote call here (like you called on room database)
--View Model
public LiveData<List<Route>> getAllRoutes()
{
//call here reposatory
return mAllRoutes;
}
//also write another method here to call repo to init a remote call
---Repository
public LiveData<List<Route>> getRoutes() {
//call on Dao
return mRouteDao.getRoutes();
}
//init a remote call
public Observable<Route> getRoutesFromNetwork(int routeID) {
return new NetworkService().GetChannel().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(String result) {
List<Route> items = new Gson().fromJson(result, new TypeToken<List<Route>>() {
}.getType());
Completable.fromRunnable(() -> {
//insert routes
//if routes is Live data it will update ui automatic
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new CompletableObserver() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onComplete() {
Log.v("Completed", "DONE");
Toasty.info(context,"DONE", Toast.LENGTH_SHORT,true).show();
}
#Override
public void onError(Throwable e) {
Log.v("Error", "Error");
}
});
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
}
});
}
In my app I am trying to use MediatorLiveData to listen to the changes to a livedata. Since DB operations are involved I use an executor service like this.
MediatorLiveData<Content> mediatorLiveData = new MediatorLiveData<>();
appExecutors.diskIO().execute(() -> {
long id = contentDao.insert(content);
Log.i("LIVE", id + "");
LiveData<Content> content = contentDao.getContentById(id);
mediatorLiveData.addSource(content, new Observer<Content>() {
#Override
public void onChanged(#Nullable Content content) {
Log.i("LIVE", "FIRED");
}
});
});
First I try to insert a new content object into the db. I get the id of the inserted object which I log in the next line. I get some id which is good. After this, I use the id to query for the same object. The query returns a LiveData. (If I use content.getValue() at this time, I get null.)
Then I listen to changes in this liveData using a MediatorLiveData. Unfortunately, the onChange method of the mediatorLiveData is never fired. Thus the Log is not printed too.
This is my content dao class
#Dao
public interface ContentDao {
#Insert
long insert(Content content);
#Query("SELECT * FROM my_table WHERE id = :id")
LiveData<Content> getContentById(long id);
}
I can't understand what I am doing wrong. Can someone please help. Thanks!!
Edit: To clarify, this is how the code looks.
return new NetworkBoundResource<Content, CreateContent>(appExecutors) {
#Override
protected void saveCallResult(#NonNull CreateContent item) {
//Something
}
#Override
protected boolean shouldCall(#Nullable Content data) {
//Something;
}
#Override
protected LiveData<Content> createDbCall() {
MediatorLiveData<Content> mediatorLiveData = new MediatorLiveData<>();
appExecutors.diskIO().execute(() -> {
long id = contentDao.insert(content);
Log.i("LIVE", id + "");
LiveData<Content> content = contentDao.getContentById(id);
mediatorLiveData.addSource(content, new Observer<Content>() {
#Override
public void onChanged(#Nullable Content c) {
Log.i("LIVE", "FIRED");
mediatorLiveData.removeSource(content);
mediatorLiveData.postValue(c);
}
});
});
return mediatorLiveData;
}
#NonNull
#Override
protected LiveData<ApiResponse<CreateContent>> createCall() {
//Something
}
}.asLiveData();
The value is returned to the constructor.
#MainThread
public NetworkBoundResource(AppExecutors appExecutors) {
this.appExecutors = appExecutors;
result.setValue(Resource.loading(null));
//TODO:: Add method to check if data should be saved. This should apply for search data.
LiveData<ResultType> dbSource = createDbCall();
result.addSource(dbSource, data -> {
result.removeSource(dbSource);
if (shouldCall(data)) {
fetchFromNetwork(dbSource);
} else {
result.addSource(dbSource, newData -> setValue(Resource.success(newData)));
}
});
}
As discussed you need to make sure the mediatorLiveData has an active observer attached.
If you take a look at the addSource method it checks whether any active observers are attached before subscribing to the source.
https://github.com/aosp-mirror/platform_frameworks_support/blob/d79202da157cdd94c2d0c0b6ee57170a97d12c93/lifecycle/livedata/src/main/java/androidx/lifecycle/MediatorLiveData.java#L95
In case anyone is re initializing a mediator live data, the old object only will be observed, new object will not be observed.
That is , dont do this:
Observe
myViewModel.observe(....)
Trying to allocate new memory to mediator
myMediatorObj = new MediatorLiveData<>(); //this can be the issue. Try removing if you have any lines like this.
//after this point,anything set to the object myMediatorObj will not be observed
In case you are trying to reset the data, pass in some data that signals null/empty/rest.
I have an application that makes requests to a 3rd party API and needs to save most of that data to a local Sqlite database (where local primary keys are autoincremented).
Those requests return a JSON response that often contains many nested objects, that I need to map and save and then link that record back to the original parent object ObjectA in this case.
{
"ObjectAList": [
{
"somefield1": "someValue1",
"someField2": "someValue2",
"nestedObjectB": {
"nestedField": "nestedValue"
},
"nestedObjectCArray": [
{
"nestedArrayField": "nestedArrayValue"
}
]
}
]
}
The app is powered by RxJava; for which I'm fairly new to. (both the networking and persistence via StorIO are reactive). I am able to set up methods to save in bulk the parent ObjectA and that works fine. However I run in to issues as I start to iterate though each of those objects using Observable.from and subsequently saving the nested child objects, collecting those records, and updating the foreign keys in their respective parent items (with usage of Observable.zip for multiple children). Often the function would be executed (according to my logs anyway), but somehow the results don't get submitted back through the rest of the chain, so I'm not sure if something went wrong or if there's an issue with my approach/implementation.
Any help or pointers on how to do this would be appreciated!
Edit some sample psudeo-code added
/*this flatmap is attached to a network request that returns
the previously defined JSON response*/
.flatMap(new Func1<List<ObjectAResponse>, Observable<List<ObjectAResponse>>>() {
#Override
public Observable<List<ObjectAResponse>> call(final List<ObjectAResponse> objectAResponse) {
return saveObjectAListToDb(someOtherKey, objectAJsonResponses)
.map(new Func1<PutResults<ObjectAEntity>, List<ObjectAResponse>>() {
#Override
public List<ObjectAResponse> call(PutResults<ObjectAEntity> putResults) {
//Returning the original response to get the nested values
return objectAResponse;
}
});
}
})
.flatMap(new Func1<List<ObjectAResponse>, Observable<ObjectAResponse>>() {
#Override
public Observable<ObjectAResponse> call(List<ObjectAResponse> objectAResponse) {
//Start emitting individual 'ObjectA' items to process its child items
return Observable.from(objectAResponse);
}
})
.flatMap(new Func1<ObjectAResponse, Observable<ObjectAEntity>>() {
#Override
public Observable<ObjectAEntity> call(ObjectAResponse objectAResponse) {
/*Saving the individual nested objects in separate functions that return an observable that contains
* the resultant entity to be updated in to the main ObjectA entity
* (in reality there could be more nested child objects to save in parallel)
*/
return Observable.zip(saveEpic(objectAResponse.nestedObjectB), saveUser(objectAResponse.nestedObjectCArray),
new Func2<ObjectBEntity, ObjectCEntity, ObjectAEntity>() {
#Override
public Object call(ObjectBEntity objectBEntity, ObjectCEntity objectCEntity) {
//Function that updates the initial object with the new entities
return updateObjectA(objectAResponse.id, objectBEntity, objectCEntity);
}
});
}
})
.collect(new Func0<List<ObjectAEntity>>() {
#Override
public List<ObjectAEntity> call() {
return new ArrayList<ObjectAEntity>();
}
},
new Action2<List<ObjectAEntity>, ObjectAEntity>() {
#Override
public void call(List<ObjectAEntity> objectAEntityList, ObjectAEntity o) {
//Collect the resultant updated entities and return the list
objectAEntityList.add(o);
}
});