在继续其余代码之前,如何等待RxJava异步调用完成?

时间:2018-11-22 14:59:33

标签: android multithreading rx-java2 android-architecture-components ui-thread

我正在使用Architecture Components。这个程序向用户展示了一堆产品。在存储库中,我有一个函数fetchProducts(),该函数应该获取数据库中尚未存在的产品。为此,我首先需要查询数据库以在其中找到最新的产品(它们都有日期),这样我就不会获取数据库中已经存在的产品。现在这显然非常重要,因为我不想做比需要的更多的工作。我如何等待异步调用完成?这是我尝试过的:

LiveData<Boolean> fetchProducts() {
    MutableLiveData<Boolean> booleanLoadingComplete = new MutableLiveData<>();
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final ProductWrapper productWrapper = new ProductWrapper();
    productDao.getMostRecentProduct()
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<ProductEntity>() {
                @Override
                public void accept(ProductEntity productEntity) throws Exception {
                    productWrapper.product = productEntity;
                    countDownLatch.countDown();
                }
            });
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // now we should be able to safely proceed with the rest of the code
    // more code goes here...

    return booleanLoadingComplete;
}

使用CountDownLatch似乎是个好主意,但是当我尝试使用此方法时,该应用程序只是冻结显示空白屏幕。

这是Dao。我是RxJava的初学者,不知道Flowable是否适合这种情况。

@Dao
public interface ProductDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(ProductEntity product);

    @Query("SELECT * FROM product ORDER BY published_at DESC")
    LiveData<List<ProductEntity>> getProducts();

    @Query("SELECT * FROM product ORDER BY published_at DESC LIMIT 1")
    Flowable<ProductEntity> getMostRecentProduct();
}

0 个答案:

没有答案
相关问题