LoginSignup
2
1

More than 5 years have passed since last update.

RxJava 2でNoSuchElementExceptionに遭う件

Posted at

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
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1