I'm trying to use RxJava / Retrofit, and I want to write an extension function to wrap some logic with the network result.
I have a class, NetworkConsumer
that extends Consumer
.
abstract class NetworkConsumer<T> : Consumer<NetworkResponse<T>> {
override fun accept(response: NetworkResponse<T>) {
if (response.isSuccessful()) {
onSuccess(response.data)
} else {
onFailure()
}
}
// other functions such as onSuccess and onFailure
}
I want to create an extension function to allow me to use the Lambda syntax like you can do with normal Consumers
.
service.login(email, password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
result ->
// result is the correct object
}, {
// handle the error
})
However, if I want to use my NetworkConsumer
, I must do:
.subscribe(object : NetworkConsumer<LoginResponse>() {
override fun onSuccess(response: LoginResponse) {
// ...
So I'm trying to write an extension function, like:
fun <T> Observable<T>.subscribe(onNext: NetworkConsumer<in T>, onError: Consumer<in Throwable>): Disposable {
return subscribe(onNext, onError, Functions.EMPTY_ACTION, Functions.emptyConsumer<Any>())
}
But it doesn't compile, the error is:
> Type mismatch.
> Required: Consumer<in T!>!
> Found: NetworkConsumer<in T>