android.os.NetworkOnMainThreadException using rxjava on android

后端 未结 4 1716
臣服心动
臣服心动 2021-01-17 12:11

i\'m having trouble implementing rxJava in order to check if there is internet connection on android i\'m doing it like this:

on my launcher activity i have this in

4条回答
  •  萌比男神i
    2021-01-17 13:03

    Observable.just(...) is called immediately on the calling thread (the main thread, in this case). Your code is effectively just an inlined version of this:

    boolean activeConn = Utils.isActiveInternetConnection(Launcher.this);
    AndroidObservable.bindActivity(this, 
            Observable.just(activeConn))
            .subscribeOn(...)
            ...
    

    You've tried to move it off the main thread by calling subscribeOn() - but the call has already happened.

    The way we handle this (and I'm not sure that this is the best way, but it works) is to defer the network or blocking call until subscription happens, set up the observable to run on the correct threads, and then subscribe:

    AndroidObservable.bindActivity(this,
            Observable.defer(new Func0() {
                @Override
                public Observable> call() {
                    return Observable.just(Utils.isActiveInternetConnection(Launcher.this));
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1() {
                @Override
                public void call(Boolean aBoolean) {
                    if (aBoolean) {
                        Toast.makeText(Launcher.this, "There is internet connection", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(Launcher.this, "There is no internet connection", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    

提交回复
热议问题