I have an activity that has a view model. When I call 2 methods of that view model first execute second method. Why?
How can I manage that methods?
This is onCreate of the activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_letter);
dbViewModel = new ViewModelProvider(this).get(DBViewModel.class);
dbViewModel.getLastUpdate().observe(this, s -> {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
try {
Date date = format.parse(s);
timeStamp = (int)date.getTime() / 1000;
getAllNews(BaseCodeClass.CompanyID, timeStamp);
} catch (ParseException e) {
e.printStackTrace();
}
});
dbViewModel.getAllNews().observe(this, newsLetters ->
{
Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();
});
}
In this method first dbViewModel.getAllNews() is executed then dbViewModel.getLastUpdate()
When you observe a LiveData
, it will call the onChanged
method on its observers when the data is ready or when the data changes. When you observe two or more LiveData
s in a certain order, it doesn't mean that the observers will be called in that order as well. It will happen sometime when the data is ready. That's exactly the behavior of observable fields like LiveData
.
If you want to read those values in that exact order and only once, you can call getValue()
and get the value right away instead of observing them:
String s = dbViewModel.getLastUpdate().getValue();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
try {
Date date = format.parse(s);
timeStamp = (int)date.getTime() / 1000;
getAllNews(BaseCodeClass.CompanyID, timeStamp);
} catch (ParseException e) {
e.printStackTrace();
}
var newsLetters = dbViewModel.getAllNews().getValue();
Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();
Those values will be read in that order, but they won't be called again if the LiveData
values change.