Search code examples
androidgenericskotlinrx-java2

Android Generic Parameter


Hi guys i have some problem passing parameter. I have 2 API call and if the device has no internet connection i need to pass the call back to another class because each api has different pojo the android give me warning mismatch type. Heres my code

 override fun initRetrofitCarList(call: Observable<Response<MyCarModel>>) {
    compositeDisposable.add(call
            .map{
              it.body()
            }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it.status == Constants.Result.SUCCESS) {
                    mPresenter.successGetVehicleList(it.vehicle, "api")
                } else {
                    mPresenter.failedGetVehicleList(it.message)
                }
            }, {
                mPresenter.onNoConnection(call) <- this here will give WARNING because of mismatch type
            }))
}

override fun initRetrofitBikeList(call: Observable<Response<MyBikeModel>>) {
    compositeDisposable.add(call
             .map{
              it.body()
            }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it.status == Constants.Result.SUCCESS) {
                    mPresenter.successGetVehicleList(it.vehicle, "api")
                } else {
                    mPresenter.failedGetVehicleList(it.message)
                }
            }, {
                mPresenter.onNoConnection(call) <- this here will give WARNING because of mismatch type
            }))
}

How to make the parameter of the function take generic call ?

EDIT

 override fun onNoConnection(//need to be generic) {
    mView.dismissProgressDialog()
    mView.showRetryDialog(call)
}

Solution

  • Just declare the function will recieve generic by putting T before function name, showRetryDialog function must also be generic, or else typecast generic to expected type (unsafe typecast)

    override fun <T> onNoConnection(call :Observable<Response<T>>){
                mView.dismissProgressDialog()
                mView.showRetryDialog(call)
    }