Proper way to setup ViewModel with LiveData and Repository with RetrofitObserving LiveData from ViewModelAccessing the same data repository in multiple viewmodels android architecture componentsRepository to return LiveData when Room doesn't have it and instead fetches from REST APISharing same MutableLiveData between Repository and ViewModelHow to use ViewModel in Android with LiveData from repository (DB/network)?How to propagate Livedata from Repository > ViewModel > FragmentHow do i use rxjava to make a retrofit request in a repository and pass it to a ViewModel using LiveData?In a repository class, how do I pass request state from a retrofit request to a ViewModel using LiveData?Implement Infinite scroll with ViewModel And Retrofit in recyclerviewIs it better to expose the LiveData object as a parameter of the ViewModel or rather returned by a member function call?
Arriving at the same result with the opposite hypotheses
PhD - Well known professor or well known school?
Why was the Sega Genesis marketed as a 16-bit console?
Passing multiple files through stdin (over ssh)
Trapping Rain Water
At what point in time did Dumbledore ask Snape for this favor?
How to return a security deposit to a tenant
What ways have you found to get edits from non-LaTeX users?
Should I compare a std::string to "string" or "string"s?
What's the name of this light airplane?
Do any instruments not produce overtones?
When 2-pentene reacts with HBr, what will be the major product?
Can anyone identify this tank?
Should an arbiter claim draw at a K+R vs K+R endgame?
An average heaven where everyone has sexless golden bodies and is bored
Implement Homestuck's Catenative Doomsday Dice Cascader
What can plausibly explain many of my very long and low-tech bridges?
Was there a priest on the Titanic who stayed on the ship giving confession to as many as he could?
What can I, as a user, do about offensive reviews in App Store?
Polymorphic keys.....definitive list?
Chemmacros scheme translation
Inconsistent behavior of compiler optimization of unused string
Soft question: Examples where lack of mathematical rigour cause security breaches?
Why only the fundamental frequency component is said to give useful power?
Proper way to setup ViewModel with LiveData and Repository with Retrofit
Observing LiveData from ViewModelAccessing the same data repository in multiple viewmodels android architecture componentsRepository to return LiveData when Room doesn't have it and instead fetches from REST APISharing same MutableLiveData between Repository and ViewModelHow to use ViewModel in Android with LiveData from repository (DB/network)?How to propagate Livedata from Repository > ViewModel > FragmentHow do i use rxjava to make a retrofit request in a repository and pass it to a ViewModel using LiveData?In a repository class, how do I pass request state from a retrofit request to a ViewModel using LiveData?Implement Infinite scroll with ViewModel And Retrofit in recyclerviewIs it better to expose the LiveData object as a parameter of the ViewModel or rather returned by a member function call?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
Currently I use a service to make network calls with retrofit
but I want to update this model to use ViewModel
with LiveData
. The thing I am struggling with is how to setup the Repository
to update the livedata object.
In the examples I have seen, people return a LiveData wrapped object in the repository something like this
public LiveData<NewsResponse> getData()
final MutableLiveData<DataResponse> data = new MutableLiveData<>();
apiService.getData().enqueue(new Callback<DataResponse>()
@Override
public void onResponse(Call<DataResponse> call, Response<DataResponse> response)
if (response.isSuccessful())
data.setValue(response.body());
@Override
public void onFailure(Call<DataResponse> call, Throwable t)
data.setValue(null);
);
return data;
then in the ViewModel
they would do
private MutableLiveData<DataResponse> dataResponse = new MutableLiveData();
private Repository repository;
public PopularGamesViewModel(@NonNull Application application)
repository = new Repository();
dataResponse = repository.getData();
public MutableLiveData<DataResponse> getData()
return dataResponse;
Then in the Activity
somewhere they would do
viewModel.getData().observe(this, dataResponse ->
if (dataResponse != null)
// Do something
);
And the thing that seems wrong to me with that is anytime I want to get new/updated data from the repository a new LiveData
object is created so previous observers wont work anymore so I would also have to set the observer again right?
How could you set it up so that you just constantly observe a LiveData
object and then from the ViewModel
call the repository to get any new data and then the ViewModel
updates the LiveData
object from the Repository
?
Does what I am suggesting make any sense?
android retrofit retrofit2 android-livedata android-viewmodel
add a comment |
Currently I use a service to make network calls with retrofit
but I want to update this model to use ViewModel
with LiveData
. The thing I am struggling with is how to setup the Repository
to update the livedata object.
In the examples I have seen, people return a LiveData wrapped object in the repository something like this
public LiveData<NewsResponse> getData()
final MutableLiveData<DataResponse> data = new MutableLiveData<>();
apiService.getData().enqueue(new Callback<DataResponse>()
@Override
public void onResponse(Call<DataResponse> call, Response<DataResponse> response)
if (response.isSuccessful())
data.setValue(response.body());
@Override
public void onFailure(Call<DataResponse> call, Throwable t)
data.setValue(null);
);
return data;
then in the ViewModel
they would do
private MutableLiveData<DataResponse> dataResponse = new MutableLiveData();
private Repository repository;
public PopularGamesViewModel(@NonNull Application application)
repository = new Repository();
dataResponse = repository.getData();
public MutableLiveData<DataResponse> getData()
return dataResponse;
Then in the Activity
somewhere they would do
viewModel.getData().observe(this, dataResponse ->
if (dataResponse != null)
// Do something
);
And the thing that seems wrong to me with that is anytime I want to get new/updated data from the repository a new LiveData
object is created so previous observers wont work anymore so I would also have to set the observer again right?
How could you set it up so that you just constantly observe a LiveData
object and then from the ViewModel
call the repository to get any new data and then the ViewModel
updates the LiveData
object from the Repository
?
Does what I am suggesting make any sense?
android retrofit retrofit2 android-livedata android-viewmodel
2
"anytime I want to get new/updated data from the repository a new LiveData object is created so previous observers wont work anymore so I would also have to set the observer again right?" -- yes. That's appropriate for some cases. For example, if instead ofgetData()
this wasgetDataForThisVerySpecificScenarioSuchAsASearchTerm()
, you may well want to have "disposable"LiveData
objects. For a case where the results of the original request might get updated, and you want to feed those updates to existing observers,MediatorLiveData
as Jiten suggests is one approach.
– CommonsWare
Mar 24 at 16:45
add a comment |
Currently I use a service to make network calls with retrofit
but I want to update this model to use ViewModel
with LiveData
. The thing I am struggling with is how to setup the Repository
to update the livedata object.
In the examples I have seen, people return a LiveData wrapped object in the repository something like this
public LiveData<NewsResponse> getData()
final MutableLiveData<DataResponse> data = new MutableLiveData<>();
apiService.getData().enqueue(new Callback<DataResponse>()
@Override
public void onResponse(Call<DataResponse> call, Response<DataResponse> response)
if (response.isSuccessful())
data.setValue(response.body());
@Override
public void onFailure(Call<DataResponse> call, Throwable t)
data.setValue(null);
);
return data;
then in the ViewModel
they would do
private MutableLiveData<DataResponse> dataResponse = new MutableLiveData();
private Repository repository;
public PopularGamesViewModel(@NonNull Application application)
repository = new Repository();
dataResponse = repository.getData();
public MutableLiveData<DataResponse> getData()
return dataResponse;
Then in the Activity
somewhere they would do
viewModel.getData().observe(this, dataResponse ->
if (dataResponse != null)
// Do something
);
And the thing that seems wrong to me with that is anytime I want to get new/updated data from the repository a new LiveData
object is created so previous observers wont work anymore so I would also have to set the observer again right?
How could you set it up so that you just constantly observe a LiveData
object and then from the ViewModel
call the repository to get any new data and then the ViewModel
updates the LiveData
object from the Repository
?
Does what I am suggesting make any sense?
android retrofit retrofit2 android-livedata android-viewmodel
Currently I use a service to make network calls with retrofit
but I want to update this model to use ViewModel
with LiveData
. The thing I am struggling with is how to setup the Repository
to update the livedata object.
In the examples I have seen, people return a LiveData wrapped object in the repository something like this
public LiveData<NewsResponse> getData()
final MutableLiveData<DataResponse> data = new MutableLiveData<>();
apiService.getData().enqueue(new Callback<DataResponse>()
@Override
public void onResponse(Call<DataResponse> call, Response<DataResponse> response)
if (response.isSuccessful())
data.setValue(response.body());
@Override
public void onFailure(Call<DataResponse> call, Throwable t)
data.setValue(null);
);
return data;
then in the ViewModel
they would do
private MutableLiveData<DataResponse> dataResponse = new MutableLiveData();
private Repository repository;
public PopularGamesViewModel(@NonNull Application application)
repository = new Repository();
dataResponse = repository.getData();
public MutableLiveData<DataResponse> getData()
return dataResponse;
Then in the Activity
somewhere they would do
viewModel.getData().observe(this, dataResponse ->
if (dataResponse != null)
// Do something
);
And the thing that seems wrong to me with that is anytime I want to get new/updated data from the repository a new LiveData
object is created so previous observers wont work anymore so I would also have to set the observer again right?
How could you set it up so that you just constantly observe a LiveData
object and then from the ViewModel
call the repository to get any new data and then the ViewModel
updates the LiveData
object from the Repository
?
Does what I am suggesting make any sense?
android retrofit retrofit2 android-livedata android-viewmodel
android retrofit retrofit2 android-livedata android-viewmodel
asked Mar 24 at 16:20
tyczjtyczj
44.4k43149234
44.4k43149234
2
"anytime I want to get new/updated data from the repository a new LiveData object is created so previous observers wont work anymore so I would also have to set the observer again right?" -- yes. That's appropriate for some cases. For example, if instead ofgetData()
this wasgetDataForThisVerySpecificScenarioSuchAsASearchTerm()
, you may well want to have "disposable"LiveData
objects. For a case where the results of the original request might get updated, and you want to feed those updates to existing observers,MediatorLiveData
as Jiten suggests is one approach.
– CommonsWare
Mar 24 at 16:45
add a comment |
2
"anytime I want to get new/updated data from the repository a new LiveData object is created so previous observers wont work anymore so I would also have to set the observer again right?" -- yes. That's appropriate for some cases. For example, if instead ofgetData()
this wasgetDataForThisVerySpecificScenarioSuchAsASearchTerm()
, you may well want to have "disposable"LiveData
objects. For a case where the results of the original request might get updated, and you want to feed those updates to existing observers,MediatorLiveData
as Jiten suggests is one approach.
– CommonsWare
Mar 24 at 16:45
2
2
"anytime I want to get new/updated data from the repository a new LiveData object is created so previous observers wont work anymore so I would also have to set the observer again right?" -- yes. That's appropriate for some cases. For example, if instead of
getData()
this was getDataForThisVerySpecificScenarioSuchAsASearchTerm()
, you may well want to have "disposable" LiveData
objects. For a case where the results of the original request might get updated, and you want to feed those updates to existing observers, MediatorLiveData
as Jiten suggests is one approach.– CommonsWare
Mar 24 at 16:45
"anytime I want to get new/updated data from the repository a new LiveData object is created so previous observers wont work anymore so I would also have to set the observer again right?" -- yes. That's appropriate for some cases. For example, if instead of
getData()
this was getDataForThisVerySpecificScenarioSuchAsASearchTerm()
, you may well want to have "disposable" LiveData
objects. For a case where the results of the original request might get updated, and you want to feed those updates to existing observers, MediatorLiveData
as Jiten suggests is one approach.– CommonsWare
Mar 24 at 16:45
add a comment |
1 Answer
1
active
oldest
votes
As far as I understood your question you want to observe the change in your livedata. for that you might want to refer to MediatorLiveData.
public LiveData<PagedList<FooPojoList>> liveData;
private MediatorLiveData<PagedList<FooPojoList>> mediatorLiveData;
public FooListViewModel(@NonNull Application application)
super(application);
mediatorLiveData=new MediatorLiveData<>();
public MediatorLiveData<PagedList<FooPojoList>> init(FooDao fooeDao,FooFrom foofrom,String orderBy)
liveData = new LivePagedListBuilder(fooDao.getAllFooList(sqliteQuery), PAGE).build();
mediatorLiveData.addSource(liveData, new Observer<PagedList<FooPojoList>>()
@Override
public void onChanged(@Nullable PagedList<FooPojoList> fooListPojos)
mediatorLiveData.setValue(fooListPojos);
);
return mediatorLiveData;
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55325882%2fproper-way-to-setup-viewmodel-with-livedata-and-repository-with-retrofit%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
As far as I understood your question you want to observe the change in your livedata. for that you might want to refer to MediatorLiveData.
public LiveData<PagedList<FooPojoList>> liveData;
private MediatorLiveData<PagedList<FooPojoList>> mediatorLiveData;
public FooListViewModel(@NonNull Application application)
super(application);
mediatorLiveData=new MediatorLiveData<>();
public MediatorLiveData<PagedList<FooPojoList>> init(FooDao fooeDao,FooFrom foofrom,String orderBy)
liveData = new LivePagedListBuilder(fooDao.getAllFooList(sqliteQuery), PAGE).build();
mediatorLiveData.addSource(liveData, new Observer<PagedList<FooPojoList>>()
@Override
public void onChanged(@Nullable PagedList<FooPojoList> fooListPojos)
mediatorLiveData.setValue(fooListPojos);
);
return mediatorLiveData;
add a comment |
As far as I understood your question you want to observe the change in your livedata. for that you might want to refer to MediatorLiveData.
public LiveData<PagedList<FooPojoList>> liveData;
private MediatorLiveData<PagedList<FooPojoList>> mediatorLiveData;
public FooListViewModel(@NonNull Application application)
super(application);
mediatorLiveData=new MediatorLiveData<>();
public MediatorLiveData<PagedList<FooPojoList>> init(FooDao fooeDao,FooFrom foofrom,String orderBy)
liveData = new LivePagedListBuilder(fooDao.getAllFooList(sqliteQuery), PAGE).build();
mediatorLiveData.addSource(liveData, new Observer<PagedList<FooPojoList>>()
@Override
public void onChanged(@Nullable PagedList<FooPojoList> fooListPojos)
mediatorLiveData.setValue(fooListPojos);
);
return mediatorLiveData;
add a comment |
As far as I understood your question you want to observe the change in your livedata. for that you might want to refer to MediatorLiveData.
public LiveData<PagedList<FooPojoList>> liveData;
private MediatorLiveData<PagedList<FooPojoList>> mediatorLiveData;
public FooListViewModel(@NonNull Application application)
super(application);
mediatorLiveData=new MediatorLiveData<>();
public MediatorLiveData<PagedList<FooPojoList>> init(FooDao fooeDao,FooFrom foofrom,String orderBy)
liveData = new LivePagedListBuilder(fooDao.getAllFooList(sqliteQuery), PAGE).build();
mediatorLiveData.addSource(liveData, new Observer<PagedList<FooPojoList>>()
@Override
public void onChanged(@Nullable PagedList<FooPojoList> fooListPojos)
mediatorLiveData.setValue(fooListPojos);
);
return mediatorLiveData;
As far as I understood your question you want to observe the change in your livedata. for that you might want to refer to MediatorLiveData.
public LiveData<PagedList<FooPojoList>> liveData;
private MediatorLiveData<PagedList<FooPojoList>> mediatorLiveData;
public FooListViewModel(@NonNull Application application)
super(application);
mediatorLiveData=new MediatorLiveData<>();
public MediatorLiveData<PagedList<FooPojoList>> init(FooDao fooeDao,FooFrom foofrom,String orderBy)
liveData = new LivePagedListBuilder(fooDao.getAllFooList(sqliteQuery), PAGE).build();
mediatorLiveData.addSource(liveData, new Observer<PagedList<FooPojoList>>()
@Override
public void onChanged(@Nullable PagedList<FooPojoList> fooListPojos)
mediatorLiveData.setValue(fooListPojos);
);
return mediatorLiveData;
edited Mar 24 at 16:46
answered Mar 24 at 16:36
Jiten BasnetJiten Basnet
320111
320111
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55325882%2fproper-way-to-setup-viewmodel-with-livedata-and-repository-with-retrofit%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
"anytime I want to get new/updated data from the repository a new LiveData object is created so previous observers wont work anymore so I would also have to set the observer again right?" -- yes. That's appropriate for some cases. For example, if instead of
getData()
this wasgetDataForThisVerySpecificScenarioSuchAsASearchTerm()
, you may well want to have "disposable"LiveData
objects. For a case where the results of the original request might get updated, and you want to feed those updates to existing observers,MediatorLiveData
as Jiten suggests is one approach.– CommonsWare
Mar 24 at 16:45