简体   繁体   English

RxJava:在另一个线程上消耗Observable的结果

[英]RxJava: Consume result of Observable on another thread

I need to perform some work on background thread and then deliver result on main thread. 我需要在后台线程上执行一些工作,然后在主线程上交付结果。 I do the following: 我执行以下操作:

Observable.just(new Object()).subscribeOn(Schedulers.newThread()).subscribeWith(new DisposableObserver<Object>() {
            @Override
            public void onNext(Object s) {

                try {
                    doSomething()
                    Observable.just(new Object())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<Object>() {
                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onNext(Object o) {
                                    completion.deliverResult()
                                    onComplete();
                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onComplete() {

                                }
                            });
                } catch (DriverException e) {
                    badThingsHappened()
                    onError(e);
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {

            }
        });

But I don't like this code, it seems complex and many things are not used. 但是我不喜欢这段代码,它看起来很复杂,并且没有使用很多东西。

Is there a way to do it more elegant? 有没有办法使它更优雅?

Your code can be converted to something similar to this one: 您的代码可以转换为与此类似的代码:


    Observable
            .create(emitter -> {
                Result result;
                try {
                    result = doSomething();
                } catch (Exception error) {
                    emitter.onError(error);
                    return;
                } finally {
                    if (result == null) {
                        emitter.onError(new IllegalStateException("Result cannot be null"));
                        return;
                    }
                }
                emitter.onNext(result);
                emitter.onComplete();
            })
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(result -> completion.deliverResult(result),
                    throwable -> badThingsHappened(throwable));

But with this approach you are mixing traditional callbacks with reactive programming: completion.deliverResult() is a standard callback. 但是,通过这种方法,您将传统的回调与响应式编程混合在一起: completion.deliverResult()是标准的回调。 Instead of doing that, return the observable stream itself and let the interested client to observe the stream itself. 而不是这样做,而是返回可观察流本身,并让感兴趣的客户端观察该流本身。

you can do what you want in few lines of codes. 您可以用几行代码来完成所需的操作。

In this snippet I'm creating a Observable object from a Callable. 在此代码段中,我将从Callable创建一个Observable对象。 The computation will be done on IO thread, but the result (or error eventually) will be observed on Android main thread 计算将在IO线程上完成,但结果(或最终出现错误)将在Android主线程上观察到

void execute() {
    // here you get your observable (api, db, other repositories). I'll create a simple String observable
    Observable<String> observable = Observable.fromCallable(
            () -> "This method will be executed on IO Thread"
    );

    // here you create your observer. I'll observe a string, so I need a Observer<String> obj
    Observer<String> stringObserver = new StringObserver();

    //now the observable will do his job on IO thread, but the result is emitted on mainThread
    observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(stringObserver);
}

class StringObserver extends DisposableObserver<String> {
    @Override
    public void onNext(String s) {
        //will be executed on main thread
    }

    @Override
    public void onError(Throwable e) {

        //will be executed on main thread
    }

    @Override
    public void onComplete() {

        //will be executed on main thread
    }
}

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

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