Skip to content

Instantly share code, notes, and snippets.

@miquelbeltran
Last active May 27, 2017 13:52
Show Gist options
  • Select an option

  • Save miquelbeltran/72cf1a9fad63d9f2fb844ef70a0e9797 to your computer and use it in GitHub Desktop.

Select an option

Save miquelbeltran/72cf1a9fad63d9f2fb844ef70a0e9797 to your computer and use it in GitHub Desktop.
class BooksViewModel extends ViewModel {
private GoogleBooksService service;
public BooksViewModel() {
// Configure Retrofit here
}
private MutableLiveData<List<Book>> books;
LiveData<List<Book>> getBooks() {
if (books == null) {
books = new MutableLiveData<List<Book>>();
}
return books;
}
public void loadBooks(String query) {
service.search("search+" + query)
// enqueue runs the request on a separate thread
.enqueue(new Callback<BookSearchResult>() {
// We receive a Response with the content we expect already parsed
@Override
public void onResponse(Call<BookSearchResult> call, Response<BookSearchResult> response) {
// Update the LiveData with fresh content
books.setValue(response.body().getBooks());
}
// In case of error, this method gets called
@Override
public void onFailure(Call<BookSearchResult> call, Throwable t) {
t.printStackTrace();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment