I fetch data from Google Books API using Architecture components. This is simple app for search book's authors. The problem is, that when I create ViewModel at first, it observes data , but when I change query to search another book's author, it does not show anything. I tried to clear ViewModel before fetch another data, it works as I wanted, but I think there must be better way for this and if there isn't let me know :)
Here is ViewModel code :
class BookViewModel extends ViewModel {
private static BookRepository repository;
BookViewModel(String q) {
repository = new BookRepository(q);
}
LiveData<String> getInfo(){
return repository.getInfo();
}
LiveData<String> getTitle(){
return repository.getTitle();
}
}
And here is the function that I call in Activity to fetch data:
public void searchBooks(View view) {
// Get the search string from the input field.
final String queryString = mBookInput.getText().toString();
if (queryString.length() != 0) {
getViewModelStore().clear();
BookViewModelFactory = new BookViewModelFactory(queryString);
BookViewModel viewModel;
viewModel=
new ViewModelProvider(this,factory).get(BookViewModel.class);
viewModel.getInfo().observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
mAuthorText.setText(s);
}
});
viewModel.getTitle().observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
mTitleText.setText(s);
}
});
mAuthorText.setText("");
mTitleText.setText(R.string.loading);
} else {
mAuthorText.setText("");
mTitleText.setText(R.string.no_search_term);
}
}else {
mAuthorText.setText("");
mTitleText.setText(R.string.no_network);
}