【发布时间】:2018-04-27 20:29:42
【问题描述】:
对于LiveData,RxJava的Observable中是否有类似blockingNext或blockingSingle的东西来同步取值?如果没有,我怎样才能实现相同的行为?
【问题讨论】:
标签: android rx-java2 android-architecture-components
对于LiveData,RxJava的Observable中是否有类似blockingNext或blockingSingle的东西来同步取值?如果没有,我怎样才能实现相同的行为?
【问题讨论】:
标签: android rx-java2 android-architecture-components
你可以调用getValue()返回当前值,如果有的话。但是,没有“阻止直到有值”选项。大多数情况下,这是因为LiveData 是在主应用程序线程上使用的,因此要避免无限期阻塞调用。
如果您需要“阻塞直到有值”,请使用 RxJava 并确保您在后台线程上进行观察。
【讨论】:
您可以使用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;
}
【讨论】: