【问题标题】:How to get value from LiveData synchronously?如何同步从 LiveData 中获取价值?
【发布时间】:2018-04-27 20:29:42
【问题描述】:

对于LiveData,RxJava的Observable中是否有类似blockingNextblockingSingle的东西来同步取值?如果没有,我怎样才能实现相同的行为?

【问题讨论】:

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


    【解决方案1】:

    你可以调用getValue()返回当前值,如果有的话。但是,没有“阻止直到有值”选项。大多数情况下,这是因为LiveData 是在主应用程序线程上使用的,因此要避免无限期阻塞调用。

    如果您需要“阻塞直到有值”,请使用 RxJava 并确保您在后台线程上进行观察。

    【讨论】:

    【解决方案2】:

    您可以使用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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      • 2018-03-30
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      相关资源
      最近更新 更多