如何同步获取LiveData的值?
How to get value from LiveData synchronously?
对于LiveData
,RxJava的Observable中有没有类似blockingNext
或者blockingSingle
的同步获取值的?如果没有,我怎样才能实现相同的行为?
您可以调用 getValue()
到 return 当前值,如果有的话。但是,没有 "block until there is a value" 选项。大多数情况下,这是因为 LiveData
旨在在主应用程序线程上使用,应避免无限期阻塞调用。
如果您需要 "block until there is a value",请使用 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;
}
使用 Kotlin 协程
callbackFlow {
val observer = Observer<Unit> {
trySend(Unit)
}
MutableLiveData<Unit>().also {
it.observeForever(observer)
awaitClose {
it.removeObserver(observer)
}
}
}.buffer(Channel.Factory.CONFLATED)
.flowOn(Dispatchers.Main.immediate)
// e.g. single()
对于LiveData
,RxJava的Observable中有没有类似blockingNext
或者blockingSingle
的同步获取值的?如果没有,我怎样才能实现相同的行为?
您可以调用 getValue()
到 return 当前值,如果有的话。但是,没有 "block until there is a value" 选项。大多数情况下,这是因为 LiveData
旨在在主应用程序线程上使用,应避免无限期阻塞调用。
如果您需要 "block until there is a value",请使用 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;
}
使用 Kotlin 协程
callbackFlow {
val observer = Observer<Unit> {
trySend(Unit)
}
MutableLiveData<Unit>().also {
it.observeForever(observer)
awaitClose {
it.removeObserver(observer)
}
}
}.buffer(Channel.Factory.CONFLATED)
.flowOn(Dispatchers.Main.immediate)
// e.g. single()