Livedata Observe not running

I tried implementing ViewModel using this. But the observe is never called.

Basically this app makes network request on the SAMPLE_URL, converts JSON to List and show the list through bookView. The app is working fine without ViewModel. With ViewModel the app runs but the observe is never called and no data is shown.

What am I doing wrong here?

BookActivity class:

 public BookAdapter bookAdapter;
    ListView bookView;
    public final static String SAMPLE_URL = "https://www.googleapis.com/books/v1/volumes?q=search+terms";
    public ArrayList<Book> books = new ArrayList<>();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activitymain);
        bookView = findViewById(R.id.list);
        bookAdapter = new BookAdapter(BookActivity.this,books);
        BookViewModel bookViewModel = new ViewModelProvider(this).get(BookViewModel.class);
        bookViewModel.getBooks().observe(this, books -> {
            Log.d("INSIDE", "observe");
            bookAdapter = new BookAdapter(this,books);
            bookView.setAdapter(bookAdapter);
            bookAdapter.notifyDataSetChanged();
        });
    }

BookViewModel class:

public class BookViewModel extends ViewModel {
    public MutableLiveData<List<Book>> books;
    public LiveData<List<Book>> getBooks(){
        if (books == null) {
            books = new MutableLiveData<>();
            loadBooks();
        }
        return books;
    }
    private void loadBooks() {
        thread.start();
    }
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            URL url = QueryUtility.createURL(BookActivity.SAMPLE_URL);
            try{
                assert url != null;
                String JSONResponse = QueryUtility.ReadFromStream(QueryUtility.MakeHTTPRequest(url));
                books = new MutableLiveData<>(QueryUtility.extractBooksFromJSON(JSONResponse));
            }
            catch (IOException | JSONException ioException){
                ioException.printStackTrace();
            }
        }
    });
}

Answer

Your thread creates a new instance of MutableLiveData for books. The original lazily-loaded instance that you probably observed is never updated. You should update the value of the existing instance.

books.postValue(QueryUtility.extractBooksFromJSON(JSONResponse));

Leave a Reply

Your email address will not be published. Required fields are marked *