Andrey
Andrey

Reputation: 53

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?

Upvotes: 0

Views: 389

Answers (2)

arungiri_10
arungiri_10

Reputation: 988

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()
    );

Upvotes: 0

zsxwing
zsxwing

Reputation: 20826

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
            });
}

Upvotes: 7

Related Questions