I am using RxJava and I need to do 2 things:
- Get the last item emitted from
Observable - Determine if it was called
onError, vs.onCompleted
I looked at using lastand lastOrDefault(actually this is the behavior I need), but I was not able to get around onErrorby hiding the last element. I would be happy if the Observable will be used twice, once to get the value lastand once to get the completion status, but so far I have managed to do this by creating my own Observer:
public class CacheLastObserver<T> implements Observer<T> {
private final AtomicReference<T> lastMessageReceived = new AtomicReference<>();
private final AtomicReference<Throwable> error = new AtomicReference<>();
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
error.set(e);
}
@Override
public void onNext(T message) {
lastMessageReceived.set(message);
}
public Optional<T> getLastMessageReceived() {
return Optional.ofNullable(lastMessageReceived.get());
}
public Optional<Throwable> getError() {
return Optional.ofNullable(error.get());
}
}
Observer, , Rx " , ". , ?