在这里研究Rx实现。
我的问题:可以在这里运行此代码而无需任何异步/可运行吗?据我了解,RX为自己创造了新线程。它可以使运行吗?此代码返回NetworkonMainThreadException
类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());
}
来自介绍者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();
}
}
您有此例外,因为您在此行中对Android Mainthread进行网络电话: URLConnection connection = myUrl.openConnection();
RX处理多线程由Schedulers
(代码中的subscribeOn(Schedulers.newThread())
(。但是您在Observable
外进行网络呼叫将您的电话包装在Observable
中,它将起作用
您的编辑代码
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());
}