Ornitologo
Ornitologo

Reputation: 39

NetworkOnMainThreadException using RX2 in Android

Here studying RX implementations.

My question: It's possible to run this code here without any asynctask/runnable? As I understand RX makes new thread for himself. Can it made runnable? This code returns NetworkOnMainThreadException

class TestInternet

public class TestInternet implements SOService.TestInternet {
    //TIMEOUT EN MILISEGUNDOS
    private final int MILISECONDS = 3000;

    @Override
    //returns the observable with connection/no connection
    public Observable <Boolean> getObservableConnection(String filter) {


            Observable<Boolean> networkAvalaible;

            try {
                    URL myUrl = new URL("http://flickr.com");
                    URLConnection connection = myUrl.openConnection();
                    connection.setConnectTimeout(MILISECONDS);
                    connection.connect();

                    networkAvalaible = Observable.just(true);

            } catch (Exception e) {
                    //I'm catching NetworkInMainThreadException here
                    e.printStackTrace();
                    networkAvalaible = Observable.just(false);
                    Log.d("error en testinternet",e.toString());
            }


            return networkAvalaible.subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread());

    }

from presenter.java

testInternet.getObservableConnection(filtro).subscribeWith(getConnectionObserver());




//comprueba conexión
public DisposableObserver<Boolean> getConnectionObserver() {
    return new DisposableObserver<Boolean>() {

        @Override                //envia los datos al recyclerview
        public void onNext(@NonNull Boolean aBoolean) {
            Log.d("rx","CONNECTION HAY NEXT");
            //envia los datos al recyclerview
            if (!aBoolean){
                Log.d("connnexcion", aBoolean.toString());
                mainView.showError(mainView.getContext().getText(R.string.no_connected).toString());
            }else if (aBoolean){
                Log.d("connnexcion", "on next correcto");
                mainView.hideError();
            }

        }

Upvotes: 0

Views: 121

Answers (1)

Marat Zangiev
Marat Zangiev

Reputation: 1382

You have this exception because you make network call on Android MainThread in this line: URLConnection connection = myUrl.openConnection(); Rx handle multithreading by Schedulers (subscribeOn(Schedulers.newThread()) in your code). But you make your network call outside an Observable Wrap your call inside an Observable and it will work

Your edited code

public class TestInternet implements SOService.TestInternet {
    //TIMEOUT EN MILISEGUNDOS
    private final int MILISECONDS = 3000;

    @Override
    //returns the observable with connection/no connection
    public Observable <Boolean> getObservableConnection(String filter) {  
        return Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                try {
                    URL myUrl = new URL("http://flickr.com");
                    URLConnection connection = myUrl.openConnection();
                    connection.setConnectTimeout(MILISECONDS);
                    connection.connect();

                    emitter.onNext(true);

                } catch (Exception e) {
                    //I'm catching NetworkInMainThreadException here
                    e.printStackTrace();
                    emitter.onNext(false);
                    Log.d("error en testinternet", e.toString());
                }
            }
        })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread()); 

    }

Upvotes: 1

Related Questions