Yannick
Yannick

Reputation: 5861

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?

Upvotes: 0

Views: 5449

Answers (1)

Chris Craik
Chris Craik

Reputation: 184

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)

Upvotes: 2

Related Questions