I have a piece of code which returns value of one field, but also initializes it:
public Observable<Integer> asObservable() {
if (subject == null) {
subject = BehaviorSubject.createDefault(0);
}
return subject;
}
I'm trying to use Optional
class to avoid if
statement:
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 methos into one with one statement only? Something similar to following won't work because subject
have not been initialized during call to ofNullable
factory method:
return Optional.ofNullable(subject)
.executeIfAbsent(() -> BehaviorSubject.createDefault(0))
.get();
Note: I'm not using original Java8 API, but aNNiMON port of this API https://github.com/aNNiMON/Lightweight-Stream-API.
How about
return subject = Optional.ofNullable(subject).orElseGet(() -> BehaviorSubject.createDefault(0));
of course, you can use a ternary conditional operator instead of creating an Optional
just to discard it immediately:
return subject != null ? subject : (subject = BehaviorSubject.createDefault(0));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With