I have a piece of code that returns the value of a single field, but also initializes it:
public Observable<Integer> asObservable() {
if (subject == null) {
subject = BehaviorSubject.createDefault(0);
}
return subject;
}
I am trying to use a class Optionalto avoid the instruction if:
public Observable<Integer> asObservableWithOptional() {
Optional.ofNullable(subject)
.executeIfAbsent(() -> BehaviorSubject.createDefault(0));
return subject;
}
Hovewer I'm still not happy with this code. Is there a way to turn this metos into one with one statement? Something similar to the following will not work, because it was subjectnot initialized during the ofNullablefactory method call :
return Optional.ofNullable(subject)
.executeIfAbsent(() -> BehaviorSubject.createDefault(0))
.get();
Note. I do not use the original Java8 API, but the aNNiMON port of this API is https://github.com/aNNiMON/Lightweight-Stream-API .