Posted at

RxJava 2でNoSuchElementExceptionに遭う件

More than 1 year has passed since last update.


NoSuchElementException

RxJava 2では、CompletableをtoMaybe()、flatMapSingle()と繋ぐと、NoSuchElementExceptionに遭遇します。

CompletableからSingleへ繋げたいパターンです。


サンプル

private Completable hoge() {

return Completable.complete();
}

private Single<String> fuga() {
return Single
.fromCallable(new Callable<String>() {
@Override
public String call() throws Exception {
return "fuga";
}
});
}

hoge()

.toMaybe()
.flatMapSingle(new Function<Object, SingleSource<String>>() {
@Override
public SingleSource<String> apply(Object o) throws Exception {
return fuga();
}
})
.subscribe(new SingleObserver<String>() {
@Override
public void onSubscribe(Disposable d) {

}

@Override
public void onSuccess(String s) {
Log.d("onSuccess", String.valueOf(s));
}

@Override
public void onError(Throwable e) {
Log.d("onError", e.toString());
}
});

出力結果

onError: java.util.NoSuchElementException


回避方法

CompletableをMaybeに変換せずにSingleに繋ぎます。

hoge()

.toSingleDefault(new Object())
.flatMap(new Function<Object, SingleSource<String>>() {
@Override
public SingleSource<String> apply(Object o) throws Exception {
return fuga();
}
})
.subscribe(new SingleObserver<String>() {
@Override
public void onSubscribe(Disposable d) {

}

@Override
public void onSuccess(String s) {
Log.d("onSuccess", String.valueOf(s));
}

@Override
public void onError(Throwable e) {
Log.d("onError", e.toString());
}
});

出力結果

onSuccess: fuga