RxJava`Completable. Andthen ` no continuous execution?

I have a use case. I initialize some global variables in a completable and use them in the next step of the chain (using the andthen operator)

The following example explains my use case in detail

Suppose you have a user class

class User {
            String name;
        }

I have an observable like this,

private User mUser; // this is a global variable

        public Observable<String> stringObservable() {
            return Completable.fromAction(() -> {
                mUser = new User();
                mUser.name = "Name";
            }).andThen(Observable.just(mUser.name));
        }

First, I'm at complete Some initialization has been done in fromaction. I hope the andthen operator will only complete the completable Start after fromaction

This means that I want to initialize muser when the andthen operator starts

Here are my subscriptions to this observation

stringObservable()
            .subscribe(s -> Log.d(TAG,"success: " + s),throwable -> Log.e(TAG,"error: " + throwable.getMessage()));

However, when I run this code, I receive an error

Attempt to read from field 'java.lang.String User.name' on a null object reference

This means that muser is null, and then in complete Start before executing code in fromaction What happened here?

According to andthen's file

Solution

The problem is not with, but with observable Just (muser. Name) statement, and then in it The just operator will attempt to create observable immediately, although it will only be used in the complete Issued after fromaction

The problem here is that muser is null when trying to create an observable using just

Solution: you need to postpone the creation of string observable until the subscription occurs, and then publish upstream

Instead of andthen (observable. Just (muser. Name));

use

andThen(Observable.defer(() -> Observable.just(mUser.name)));

or

andThen(Observable.fromCallable(() -> mUser.name));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>