package com.dahe.gldriver.net

import android.content.Context
import com.dahe.mylibrary.net.CommonResponseBean
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable

/**
 * 自定义观察者
 */
class BaseObserver<T>(
    private val mContext: Context,
    private val mRxHttpCallBack: RxHttpCallBack<T>
) : Observer<CommonResponseBean<T>> {
    private var disposable: Disposable? = null

    /**
     * 订阅成功
     *
     * @param d
     */
    override fun onSubscribe(d: Disposable) {
        disposable = d
        mRxHttpCallBack.onStart()
    }

    override fun onNext(tCommonResponseBean: CommonResponseBean<T>) {
        if (200 == tCommonResponseBean.code) {
            mRxHttpCallBack.onSuccess(tCommonResponseBean)
        } else {
            mRxHttpCallBack.onCodeError(mContext, tCommonResponseBean)
        }
    }

    override fun onError(e: Throwable) {
        mRxHttpCallBack.onFailure(mContext, e)
        if (disposable != null && disposable!!.isDisposed) {
            disposable!!.dispose()
        }
    }

    override fun onComplete() {}
}