简体   繁体   中英

how to convert AsyncTask to RxAndroid

I am new to rxandroid, now I want to use rxandroid to access internet with out use AsyncTask, I have write some code below

```

 Observable<String> o= Observable.create(new Observable.OnSubscribe<String>() {

       @Override
       public void call(Subscriber<? super String> sub) {
           sub.onNext("http://192.168.191.1/test3.html");//The test url in my computer ,it works ok;
       }
   });
    Subscriber<String> mySubscriber = new Subscriber<String>() {
        @Override
        public void onNext(String s) {
            InputStream in = null;
            try {
                in = new URL(s).openStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Reader r = null;
            try {
                r = new InputStreamReader(in, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            char[] buffer = new char[8000];
            try {
                r.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.d("AAA", new String(buffer));
        }

        @Override
        public void onCompleted() { }

        @Override
        public void onError(Throwable e) { }
    };
    o.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(mySubscriber);

```

It haven't cause any crash, but I can not get any output, anyone know how to solve it? Thank you very much.

It does not appear that you actually do anything with your results or update your UI, which would cause you not to see any results. The composition of your RX code looks pretty decent, so I believe that this is why.

Rx-Android has largely since been rolled into RX-Binding so you should use that instead.

I just was working on this myself to populate a listview with results from my rest interface:

AsyncTask replacement with RXJava help needed

What you're doing looks good but you can simplify it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM