简体   繁体   中英

how to change from android asynctask to rxandroid?

I've been working with asynctask But I can't use asynctask anymore

So I decided to use rxandroid and changed it as below It seems to work, but I'm not sure if I'm using it properly Could you give me any advice? Thank you

for(int i=0;i<10;i++)
{
    new AppTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,data[i]);
}

to

for(int i=0;i<10;i++)
{
    Observable observable = Observable.just(data);

    observable
            .subscribeOn(Schedulers.newThread())
            //.observeOn(AndroidSchedulers.mainThread())
            .subscribe(observer);
}

Observer<String> observer = new Observer<String>() {
    @Override
    public void onSubscribe(Disposable d) {
        
    }

    @Override
    public void onNext(String s) {
        process(s);

    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onComplete() {

    }
};

To emit a consecutive range of integers, you can use Observable.range(). This will emit each number from a start value and increment each emission until the specified count is reached.

  Observable.range(1,10).subscribe(s -> System.out.println("RECEIVED: " + s));

output:

 RECEIVED:1 RECEIVED:2 RECEIVED:3 RECEIVED:4 RECEIVED:5 RECEIVED:6 RECEIVED:7 RECEIVED:8 RECEIVED:9 RECEIVED:10

In your case, you can pass up to 10 items with just

Observable.just("one", "two", "three", ... ,"ten");

You can also use Observable.fromIterable() to emit the items from any Iterable type, such as a List . It also will call onNext() for each element and then call onComplete() after the iteration is complete.

Schedulers.newThread() may be helpful in cases where you want to create, use, and then destroy a thread immediately so it does not take up memory. But for complex applications generally, you will want to use Schedulers.io() so there is some attempt to reuse threads if possible. You also have to be careful as Schedulers.newThread() can run amok in complex applications (as can Schedulers.io() ) and create a high volume of threads, which could crash your application.

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