简体   繁体   中英

Android Adapter formats layout before onDataSetChanged has had time to process the data

I'm implementing an instance of RemoteViewsService.RemoteViewsFactory which controls the layout for my widget. The problem is the data to format the layouts gets pulled from the database and formatted asynchronously via RxJava2.

@Override
public void onDataSetChanged() {
    Observable.doSomeLongAsyncRequestAndProcess()
        .subscribe(data -> {
            // Data is ready at this point
            // Unfortunately it's too late
        })
}


@Override
public RemoteViews getViewAt(int position) { // layout with non-existant data }

Since I don't control (not that I know of) when the layout starts initiating the layout in, how can I stop #getViewAt from trying to process the layout before the data's ready?

Short answer : Just fetch your data from database in onDataSetChanged() without async. Something like:

Observable.doSomeLongAsyncRequestAndProcess()
    .subscribe(data -> {
        // Data is ready at this point
        // And after that, chain to getViewAt() will be triggered, 
        // so you will have all your data for views in time
    }).blockingFirst()

Long answer : onDataSetChanged() is working on binder thread, so it will be safe to fetch data here. In RemoteViewFactory callbacks, only onCreate() is on main thread. You can easily check it by logging current thread in all callbacks of RemoteViewFactory. So there will be no problem anymore, after executing onDataSetChanged() , it will trigger chain to getViewAt() , and you will have already all data for your remoteviews list at this moment. 在此处输入图片说明

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