首页 > 解决方案 > 是否有 Handler.runWithScissors(final Runnable r, long timeout) 的 RxJava(Rxandroid) 等价物?

问题描述

是否有 Handler.runWithScissors(final Runnable r, long timeout) 的 RxJava(Rxandroid) 等价物?

我有一个问题是workerThread异步获取长时间运行的结果。( mApplication.startApp())

同时通知中的进度uiThread,我的解决方法如下:


/**
 * @return Observable<String> that subscribe the progress.
 */
public Observable<String> startApp() {
        Subject<String> mAppState = BehaviorSubject.create();

        Observable.just("Initialize...")
                .observeOn(mSchedulerProvider.single())
                .doOnNext((state) -> {
                    mAppState.onNext(state);
                    mApplication.startApp();
                })
                .doOnError((error) -> mAppState.onError(error))
                .map((state) -> "Initialization Complete.")
                .doOnNext((state) -> {
                    TimeUnit.MILLISECONDS.sleep(1000);
                    mAppState.onNext(state);
                    mAppState.onComplete();
                })
                .compose(bindToLifecycle())
                .subscribe();

        return mAppState.compose(bindToLifecycle())
                .observeOn(mSchedulerProvider.ui());
    }

有人有更好的解决方案吗?谢谢。

标签: androidrx-java2

解决方案


我不认为你的解决方案很好

    Observable.just(1)
            .observeOn(Schedulers.computation())
            .map(integer -> {
                // do your long job or computation
                return integer;
            })
            .skip(1, TimeUnit.SECONDS)
            .observeOn(AndroidScheduler.mainThread())
            .map(o -> {
                //UI update
                return o;
            }).subscribe();

推荐阅读