如何同步从LiveData获取价值?

时间:2018-04-27 20:29:43

标签: android rx-java2 android-architecture-components

对于LiveData,RxJava的Observable中是否有与blockingNextblockingSingle类似的内容来同步获取值?如果没有,我怎么能达到同样的行为?

2 个答案:

答案 0 :(得分:4)

您可以致电getValue()以返回当前值(如果有)。但是,没有"阻止,直到有一个值"选项。大多数情况下,这是因为LiveData意味着要在主应用程序线程上使用,其中要避免无限期阻塞调用。

如果您需要"阻止直到有值",请使用RxJava并确保您在后台线程上观察。

答案 1 :(得分:0)

您可以使用Future来像这样同步数据:

 LiveData<List<DataModel>> getAllDatasForMonth(final String monthTitle) {
    Future<LiveData<List<DataModel>>> future = DatabaseHelper.databaseExecutor
            .submit(new Callable<LiveData<List<DataModel>>>() {
        @Override

        public LiveData<List<DataModel>> call() throws Exception {
            mAllDatasForMonth = mDataDao.getDatasForMonth(monthTitle);
            return mAllDatasForMonth;
        }
    });
    try {
        //with get it will be wait for result. Also you can specify a time of waiting.
        future.get();
    } catch (ExecutionException ex){
        Log.e("ExecExep", ex.toString());
    } catch (InterruptedException ei) {
        Log.e("InterExec", ei.toString());
    }
    return mAllDatasForMonth;
}