I have a usecase where I initiallize some global variables in a Completable , and in the next step in the chain (using andThen
operator) I make use of those variables.
Following sample explains my usecase in detail
Say you have a class User
class User {
String name;
}
and 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 doing some initiallizations in my Completable.fromAction
and I expect andThen
operator to start only after completing the Completable.fromAction
.
Which means I expect mUser
to be initallized when the andThen
operator starts.
Following is my subscription to this observable
stringObservable()
.subscribe(s -> Log.d(TAG, "success: " + s),
throwable -> Log.e(TAG, "error: " + throwable.getMessage()));
But when I run this code , I get an error
Attempt to read from field 'java.lang.String User.name' on a null object reference
which means mUser
is null , andThen
started before executing the code in Completable.fromAction
. Whats happening here?
According to documentation of andThen
Returns an Observable which will subscribe to this Completable and once that is completed then will subscribe to the {@code next} ObservableSource. An error event from this Completable will be propagated to the downstream subscriber and will result in skipping the subscription of the Observable.
Observable.just(T)
docs states: "Note that the item is taken and re-emitted as is and not computed by any means by just. UsefromCallable(Callable)
to generate a single item on demand (when Observers subscribe to it)." – Neoteric