ProgressSubscriber.java 2.58 KB
package com.huaheng.robot.https.Subscribers;

import android.content.Context;
import android.widget.Toast;

import com.huaheng.robot.LoginActivity;
import com.huaheng.robot.R;
import com.huaheng.robot.https.ProgressCancelListener;
import com.huaheng.robot.https.ProgressDialogHandler;
import com.huaheng.robot.util.SoundUtils;
import com.huaheng.robot.util.WMSLog;
import com.huaheng.robot.util.WMSUtils;

import rx.Subscriber;


public class ProgressSubscriber<T> extends Subscriber<T> implements ProgressCancelListener {

    private SubscriberOnNextListener mListener;
    private ProgressDialogHandler progressHandler;

    private Context context;

    public ProgressSubscriber(Context context, SubscriberOnNextListener mListener) {
        this.context = context;
        this.mListener = mListener;

        progressHandler = new ProgressDialogHandler(context, this, false);
    }

    private void showProgressDialog() {
        if (progressHandler != null) {
            progressHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog() {
        if (progressHandler != null) {
            progressHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            progressHandler = null;
        }
    }


    @Override
    public void onStart() {
        WMSLog.d("onStart");
        showProgressDialog();
    }

    @Override
    public void onCompleted() {
        WMSLog.d("onCompleted");
        dismissProgressDialog();
    }

    @Override
    public void onError(Throwable e) {
        dismissProgressDialog();
        SoundUtils.getInstance(context).errorSound();
        e.printStackTrace();
        if(e.getMessage() != null) {
            WMSLog.d("onError:" + e.getMessage());
            if (e.getMessage().contains(context.getString(R.string.login_again))) {
                WMSUtils.startActivity(context, LoginActivity.class);
            }
            Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
        } else {
            if(e.toString() != null && e.toString().contains("SocketTimeoutException")) {
                Toast.makeText(context, context.getString(R.string.http_sockettime), Toast.LENGTH_SHORT).show();
            }
        }
        mListener.onError(e.getMessage());
    }

    @Override
    public void onNext(T t) {
        WMSLog.d("onNext t:" + t);
        mListener.onNext(t);
    }

    @Override
    public void onCancelProgress() {
        WMSLog.d("onCancelProgress");
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }
}