简体   繁体   中英

LiveData: Cannot invoke observeForever on a background thread after AndroidX refactor

After refactoring to androidx (via AndroidStudio) my PageKeyedDataSource from the Pagination Libary breaks because of this error:

 java.lang.IllegalStateException: Cannot invoke observeForever on a background thread

Code:

class TransactionDataSource(val uid: String, groupIdLiveData: LiveData<GroupNameIdPair>, var groupId: String) : PageKeyedDataSource<DocumentSnapshot, Transaction>() {
[...]
    init {
                val observer: Observer<GroupNameIdPair> = {
                    invalidate()
                    groupId = it.id

                }
                groupIdLiveData.observeNotNull(observer)
        }
[...]

Since the PageKeyedDataSource is executed on background by default and relies on LiveData i wonder why this breaks in Version 2.0.0 of LifeData (AndroidX refactor). Is this a bug and is there a way to make it work again?

Looks like your refactor to AndroidX updated you to the version of LiveData which requires observation on the main thread. You'd also see this if you updated to the latest pre-androidx version of LiveData, 1.1.1.

Observing LiveData can't be done off the UI thread, but depending on what you're doing that may be fine. If your DataSource isn't actually doing any loading, you can tell the Paging library to use an executor wrapping the UI/Main thread:

static Executor MainExecutor = new Executor() {
    Handler handler = new Handler(Looper.getMainLooper());
    @Override
    public void execute(Runnable runnable) {
        handler.post(runnable);
    }
};

and pass it to the Paging library (assuming you're using LiveData<PagedList> )

LivePagedListBuilder.create(myFactory, myConfig)
        //...
        .setFetchExecutor(MainExecutor)
        .build();

(If you're using RxPagedListBuilder, there's a similar setFetchScheduler() method)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM