简体   繁体   English

Livedata 观察未运行

[英]Livedata Observe not running

I tried implementing ViewModel using this .我尝试使用这个实现 ViewModel。 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.基本上这个应用程序在 SAMPLE_URL 上发出网络请求,将 JSON 转换为 List 并通过 bookView 显示列表。 The app is working fine without ViewModel.该应用程序在没有 ViewModel 的情况下运行良好。 With ViewModel the app runs but the observe is never called and no data is shown.使用 ViewModel 时,应用程序会运行,但不会调用观察,也不会显示任何数据。

What am I doing wrong here?我在这里做错了什么?

BookActivity class:图书活动 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: 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();
            }
        }
    });
}

Your thread creates a new instance of MutableLiveData for books .您的线程为books创建了一个新的 MutableLiveData 实例。 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM