简体   繁体   中英

RxAndroid with parameterized AsyncTask

I want to rewrite project using rxAndroid. In my code i have this simple part:

public void chkLogin(String login, String password) {
    String[] myTaskParams = { login, password };
    new ChkLoginTask().execute(myTaskParams);
}

private class ChkLoginTask extends AsyncTask<String, Void, LoginStatus> {
    @Override
    protected void onPreExecute(){
        view.showLoadingSpinner();
    }

    @Override
    protected LoginStatus doInBackground(String... params) {
        return app.getAPI().checkLogin(params[0], params[1]);
    }

    @Override
    protected void onPostExecute(LoginStatus result) {
        view.hideLoadingSpinner();
        if(result == null)
            view.onConnectionError();
        else{
            view.onChkLoginSuccess(result);
        }
    }
}

In this code i just call my api method in AsyncTask with two params and then react by view on it's result.

Now I want to write this code using rxAndroid, but I'm stuck on it... I know how rx work with react on UI elements, but can't find information about how it works with parameterized AsyncTask

And does it correct to use RX in this case?

Since you want to use RxJava, you don't need AsyncTask any more. You can rewrite your codes using subscribeOn and observeOn like this:

public void chkLogin(String login, String password) {
    view.showLoadingSpinner();
    Observable.defer(() -> Observable.just(app.getAPI().checkLogin(login, password)))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(result -> {
                view.hideLoadingSpinner();
                if (result == null)
                    view.onConnectionError();
                else {
                    view.onChkLoginSuccess(result);
                }
            }, e -> {
                // handle the exception
            });
}

Based on the Async task code above, converting it to Rx.

String[] myTaskParams = { login, password };
Observable
    //Pass login and password array
    .just(myTaskParams)
    //Array is received below and a api call is made
    .map(
        loginCredentials -> app.getAPI().checkLogin(loginCredentials[0], loginCredentials[1])
    )
    .doOnSubscribe(disposable -> view.showLoadingSpinner())
    .doOnComplete(() -> view.hideLoadingSpinner())
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(
        result -> result == null ? view.onConnectionError() : view.onChkLoginSuccess(result),
        error -> view.onConnectionError()
    );

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