I am getting User from Room Database by returning Single<UserMinimal>. Once I get the data I want to show it through LiveData observing, and I am using LiveDataReactiveStreams.fromPublisher() method, but looks like when .setValue() is called, all attributes of the received user are null. Don't know if needs .subscribe() or whatever.
LiveData<UserMinimal> userLiveData = LiveDataReactiveStreams
.fromPublisher(mRepository.getUser().toFlowable());
user = new MediatorLiveData<>();
user.addSource(userLiveData, minimalUser -> {
user.postValue(minimalUser);
user.removeSource(userLiveData);
});
public Single<MenuRepository.UserMinimal> getUser(){
return dataSource.getUser()
.onErrorReturnItem(new MenuRepository.UserMinimal())
.doOnError(t -> Timber.e(t))
.subscribeOn(Schedulers.io());
}
Looks like the access to database is successfully working because if I use MutableLiveData instead of MeadiatorLiveData, it does work:
user = new MutableLiveData<>();
disposable.add(mRepository.getUser().subscribe(new Consumer<UserMinimal>() {
#Override
public void accept(UserMinimal userMinimal) throws Throwable {
user.postValue(userMinimal);
}
}));
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'm building an offline-first app with the database setup as the single source of truth. I am using Room to simplify the database handling, and LiveData to simplify observable data patterns.
I am also using Retrofit to make any network calls required to populate the database with new data.
I have set up an observer in my Fragment as follows:
private void setUpObserver() {
tfViewModel = ViewModelProviders.of(getActivity()).get(TFViewModel.class);
tfViewModel.getAllPosts().observe(getActivity(),
newPosts -> {
if (newPosts != null && newPosts.size() > 0) {
lottieAnimationView.setVisibility(View.INVISIBLE);
mPostsAdapter.updateItems(newPosts);
}
});
tfViewModel.fetchNextData(currentPage);
}
When my app first starts, I'm deleberately truncating each table in my database using Room callbacks so that new data is fetched every time. (For testing. This beats the offline-first experience and must not be done in production.)
Anyway, so when it first starts, it calls the fetchNextData method of the viewmodel which in turn asks the Repository to fetch the data.
Here's my ViewModel:
public class TFViewModel extends AndroidViewModel {
private TFRepository mRepository;
private LiveData<List<Post>> mPostList;
public TFViewModel(Application application) {
super(application);
mRepository = new TFRepository(application);
mPostList = mRepository.getAllPosts();
}
public LiveData<List<Post>> getAllPosts() {
return mPostList;
}
public void fetchNextData(int page) {
mRepository.fetchNextPosts(page);
}
}
In the repository, I use my DAOs to insert posts into the database. To fetch new data, I use a Service Class to fetch new data for me. When the fetch call returns, I use an AsyncTask to insert the new posts to my database. (Details omitted for brevity):
public class TFRepository {
private PostDao postDao;
private LiveData<List<Post>> postList;
private RetrofitSingleton retrofitSingleton;
public TFRepository(Application application) {
TFRoomDatabase db = TFRoomDatabase.getDatabase(application);
postDao = db.postDao();
retrofitSingleton = RetrofitSingleton.getInstance(application.getApplicationContext());
postList = postDao.getAllPosts();
}
public LiveData<List<Post>> getAllPosts() {
return postList;
}
public void fetchNextPosts(int page) {
getPostList(page);
}
private void getPostList(int page) {
APICaller.getInstance(retrofitSingleton).getFeed(page,
new NetworkResponseListener<BaseResponse<FeedResponse>>() {
#Override
public void onResponseReceived(BaseResponse<FeedResponse> feedResponseBaseResponse) {
if (feedResponseBaseResponse == null) return;
List<Post> posts = feedResponseBaseResponse.getData().getPosts();
new insertAllPostsAsyncTask(postDao).execute(posts);
}
#Override
public void onError(String errorMessage) {
}
});
}
}
The OBSERVER I had setup in my fragment gets an empty list the first time around. The API call returns with the first page of posts and it receives 10 posts the second time. The view is popualted. Everything is good.
Problem: As the user scrolls down, the Fragment asks the ViewModel to fetch more data. The ViewModel asks the Repository to fetch new data. The Retrofit call goes and comes back with the new data. It is inserted in the database. BUT THE OBSERVER IS NOT NOTIFIED. What am I missing?
NOTE: I do not want to use a MutableLiveData as I want to maintain the DB as the single source of truth. Also, as the docs state that LiveData is notified whenever the underlying DB changes, my implementation should work with LiveData.
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 a list of Observables like so:
List<Observable<MyObj>> listObservables = new ArrayList<Observable<MyObj>>();
I'd like to combine all Observable in a single one, I can handle it if I know the number of Observable using zip(), for example we have 3 Observable:
Observable<MyObj1> obs1= MyRestClient.getSomeData1();
Observable<MyObj2> obs2= MyRestClient.getSomeData2();
Observable<MyObj3> obs3= MyRestClient.getSomeData3();
I have a wrapper obj:
class MyWrapperObj {
private MyObj1 onj1;
private MyObj2 onj2;
private MyObj3 onj3;
public MyWrapperObj(MyObj1 onj1, MyObj2 onj2, MyObj3 onj3) {
this.onj1 = onj1;
this.onj2 = onj2;
this.onj3 = onj3;
}
}
So I can combine them like so:
Observable<MyWrapperObj> combinedObservable = Observable.zip(obs1, obs2, obs3, new Func3<MyObj1, MyObj2, MyObj3, MyWrapperObj>() {
#Override
public MyWrapperObj call(MyObj1 obj1, MyObj2 obj2, MyObj3 obj3) {
return new MyWrapperObj(obj1, obj2, obj3);
}
});
combinedObservable.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<MyWrapperObj>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable throwable) {
}
#Override
public void onNext(MyWrapperObj wrapperObj) {
}
});
Everything is working fine, so my problem is how to organize this combination to be for n Observable?
RESPONSE
as #maciekjanusz mentioned in it's answer I did:
Observable<MyWrapperObj> combinedObservable = Observable.zip(listObservables, new FuncN<MyWrapperObj>() {
#Override
public MyWrapperObjcall(Object... args) {
return null;
}
});
If you want to zip n Observables, put them in a list and apply the public static <R> Observable<R> zip(#NotNull java.lang.Iterable<? extends Observable<?>> ws, rx.functions.FuncN<? extends R> zipFunction) factory method.
List<Observable<String>> observables = Arrays.asList(Observable.just("String 1"), Observable.just("String 2"));
Observable.zip(observables, args -> {
// put your zipping code here
});
For example, if you want to create a list of strings for each emission from all observables:
Observable.zip(observables, Arrays::asList);
Or, if using RxJava on android without retrolambda:
Observable.zip(observables, args -> Arrays.asList(args));
Suppose you have the list:
List<Observable<MyObj>> listObservables
You might consider using Observable.concatDelayError
The advantage if it is finishing all Obbservable's even if any of them finishes with error (resulting in an error in such case).
Remember, that every Observable in this sequence must return the result to onNext method of Subscriber. The result also must have the same type.
Example:
Observable.concatDelayError(listObservables);
You can wait until all observables is complete by using
.zip(observable1, ..., observableN, funcN).first() operators. There is an overload, accepting Observable> argument (as in FlatMap).
First overload takes Iterable> - you can pass list of observables of arbitrary size and second argument - FuncN - receives list of values.