1. 程式人生 > >使用Rxbus通知Activity頁面重新整理,不立刻重新整理,延遲到activity onResume 後才重新整理

使用Rxbus通知Activity頁面重新整理,不立刻重新整理,延遲到activity onResume 後才重新整理

1.使用Rxbus通知Activity頁面重新整理,不立刻重新整理,延遲到activity onResume 後才重新整理

RxBus.getDefault().toObservable(ReportUpdateEvent.class)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                //延遲收到重新整理訊息
                .compose(new Observable.Transformer<ReportUpdateEvent, ReportUpdateEvent>() {
                    @Override
                    public Observable<ReportUpdateEvent> call(Observable<ReportUpdateEvent> reportUpdateEventObservable) {
                        Func1<ActivityEvent, Boolean> func1=new Func1<ActivityEvent, Boolean>() {
                            @Override
                            public Boolean call(ActivityEvent activityEvent) {
                                return activityEvent.equals(ActivityEvent.RESUME);
                            }
                        };
//延遲傳送事件給訂閱者,直到收到activity的Resume事件
                        Observable<ActivityEvent>  o=lifecycleProvider.lifecycle().takeFirst(func1);
//delay 除了可以設定時間,還可以放觀察者
                         return  reportUpdateEventObservable.delay(new Func1<ReportUpdateEvent, Observable<ActivityEvent>>() {
                             @Override
                             public Observable<ActivityEvent> call(ReportUpdateEvent reportUpdateEvent) {
//o是activity生命週期的觀察者
                                 return o;
                             }
                         });

                    }
                })
                .subscribe(event -> {
                    Log.e("MyReportListViewModel","收到重新整理事件");
                    if (event.isRefresh()) {
                        // 新增報事成功後,返回重新整理報事頁面。
                        requestData(1);
                    }
                }, throwable -> {

                }

2.優化一下程式碼

RxBus.getDefault().toObservable(ReportUpdateEvent.class)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                //延遲收到重新整理訊息
                .compose(RxUtil.delayTransformerByLife(lifecycleProvider))
                .subscribe(event -> {
                    Log.e("MyReportListViewModel","收到重新整理事件");
                    if (event.isRefresh()) {
                        // 新增報事成功後,返回重新整理報事頁面。
                        requestData(1);
                    }
                }, throwable -> {

                })
public class RxUtil {

   
    public static <T> Observable.Transformer<T, T> delayTransformerByLife(LifecycleProvider<?> lifecycleProvider){
        return observable-> observable.delay((o)->{
            return lifecycleProvider.lifecycle().takeFirst(((activityEvent)->{
                return activityEvent.equals(ActivityEvent.RESUME);
            }));
        });
    }
}