How to get value from LiveData synchronously?

只谈情不闲聊 提交于 2021-01-21 07:44:07

问题


For LiveData, is there something similar to blockingNext or blockingSingle in RxJava's Observable to get the value synchronously? if not, how can i achieve the same behavior?


回答1:


You can call getValue() to return the current value, if there is one. However, there is no "block until there is a value" option. Mostly, that is because LiveData is meant to be consumed on the main application thread, where indefinitely-blocking calls are to be avoided.

If you need "block until there is a value", use RxJava and ensure that you are observing on a background thread.




回答2:


You can use Future to synchronize your data like this:

 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;
}


来源:https://stackoverflow.com/questions/50069857/how-to-get-value-from-livedata-synchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!