package com.dahe.pass.net;

import android.content.Context;

import com.dahe.mylibrary.net.CommonResponseBean;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;


/**
 * 自定义观察者
 */

public class BaseObserver<T> implements Observer<CommonResponseBean<T>> {
    private Context mContext;
    private RxHttpCallBack<T> mRxHttpCallBack;
    private Disposable disposable;

    public BaseObserver(Context mContext, RxHttpCallBack<T> mRxHttpCallBack) {
        this.mContext = mContext;
        this.mRxHttpCallBack = mRxHttpCallBack;
    }

    /**
     * 订阅成功
     *
     * @param d
     */
    @Override
    public void onSubscribe(@NonNull Disposable d) {
        this.disposable = d;
        mRxHttpCallBack.onStart();
    }


    @Override
    public void onNext(CommonResponseBean<T> tCommonResponseBean) {
        if (200==tCommonResponseBean.getCode()) {
            mRxHttpCallBack.onSuccess(tCommonResponseBean);
        } else {
            mRxHttpCallBack.onCodeError(mContext, tCommonResponseBean);
        }
    }

    @Override
    public void onError(Throwable e) {
        mRxHttpCallBack.onFailure(mContext, e);
        if (disposable!=null&&disposable.isDisposed()){
            disposable.dispose();
        }
    }

    @Override
    public void onComplete() {

    }

}
