简体   繁体   English

Android适配器在onDataSetChanged有时间处理数据之前格式化布局

[英]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. 我正在实现一个RemoteViewsService.RemoteViewsFactory实例,该实例控制我的小部件的布局。 The problem is the data to format the layouts gets pulled from the database and formatted asynchronously via RxJava2. 问题是用于格式化布局的数据已从数据库中提取出来,并通过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? 由于我不控制(不知道)布局何时开始初始化布局,因此如何在数据准备就绪之前阻止#getViewAt尝试处理布局?

Short answer : Just fetch your data from database in onDataSetChanged() without async. 简短的答案 :只需从onDataSetChanged()中的数据库中获取数据即可,而无需异步。 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. 长答案onDataSetChanged()正在绑定程序线程上工作,因此在此处获取数据将是安全的。 In RemoteViewFactory callbacks, only onCreate() is on main thread. 在RemoteViewFactory回调中,仅onCreate()在主线程上。 You can easily check it by logging current thread in all callbacks of RemoteViewFactory. 您可以通过在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. 因此,在执行onDataSetChanged()之后 ,将不再有问题,它将触发到getViewAt()的链,并且此时您已经拥有了远程视图列表的所有数据。 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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