Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@daisuke_nomura

RxJava 2でNoSuchElementExceptionに遭う件

More than 3 years have 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
1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
daisuke_nomura
Android app developer, Railfan.

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?