dotGitignore
dotGitignore

Reputation: 1627

How to properly handle generic types?

I am trying to create a custom function that will handles all my API response, but I don't know how to properly handle it.

This is my code

My Custom callback

interface ResponseCallback<T> {
    fun onSuccess(response: T)
    fun onError(code: Int, message: String)
}

This is how I call my request API

createRequest(getLogin(id), object : API.ResponseCallback<LoginResponse>{
    override fun onError(code: Int, message: String) {
    }

    override fun onSuccess(response: LoginResponse) {
    }
})

and This is how I handle my request

fun createRequest(source: Observable<*>, callback: ResponseCallback<*>) {
    disposable.add(
        source.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                { it ->
                    //
                    // callback.onSuccess(it)

                },
                {

                }
            )
    )
}

but my problem here is, the callback.onSuccess() parameter is Nothing and can't accept the callback.onSuccess(it)

Please help me, Thanks.

Upvotes: 1

Views: 417

Answers (1)

zsmb13
zsmb13

Reputation: 89528

You should only use star projections if you don't know the specific type parameter for a generic type. When you use these, the compiler will prevent you from doing unsafe things with the parameterized type. For example, you've seen that you can't pass in any parameter to onSuccess, since you've essentially told the compiler that you don't know what its type should be.

The fix then is to give your createRequest function a type parameter instead, and make both the Observable be of that type, as well as the callback that you wish to invoke:

fun <T> createRequest(source: Observable<T>, callback: ResponseCallback<T>) {
    ...
    callback.onSuccess(it) // works, since you're passing in a T to a method that requires a T
    ...
}

Upvotes: 1

Related Questions