Add extra parameter for a method from a defined interface

I’m trying to create a custom Consumer (RxJava) implementation that will handle some exceptions (i.e. InternetConnectionException).

I’m using MVP and when I get InternetConnectionException I need to call mViewDelegate.onError(throwable.getMessage()) and I want to pass that method as onError: () -> Unit to my consumer.

What I want to achieve looks like this:

new TestConsumer() {
   @Override
    public void accept(Throwable throwable) throws Exception {
         super.accept(throwable, () -> mViewDelegate.onError(throwable.getMessage()));
}

What I came up with is this:

abstract class TestConsumer : Consumer<Throwable> {

    lateinit var onError: () -> Unit

    @Throws(Exception::class)
    override fun accept(throwable: Throwable?) {
        throwable?.let {
            if (throwable is InternetConnectionException) {
                onError()
            } else {
                throw throwable
            }
        }
    }

}

but I also need to set onError like this:

new TestConsumer() {
    @Override
    public void accept(Throwable throwable) throws Exception {
        super.accept(throwable);
        super.onError = () -> mViewDelegate.onError(throwable.getMessage());
}

Are there any better approaches?

You could make TestConsumer non-abstract, and add a lambda parameter to its constuctor called onError.

That is nicer to use, and avoids mutable state.

I won’t be able to pass mViewDelegate.onError(throwable.getMessage()) to the constructor for I don’t have that throwable.

make the lambda take a Throwable, then pass the accept’s argument to it.

I don’t get it…

class TestConsumer(private val onError:(t: Throwable) -> Unit) : Consumer<Throwable> {

    @Throws(Exception::class)
    override fun accept(throwable: Throwable?) {
        throwable?.let {
            if (throwable is InternetConnectionException) {
                onError(throwable)
            } else {
                throw throwable
            }
        }
    }
}

You then create it like this:

val consumer = TestConsumer { throwable -> mViewDelegate.onError(throwable.getMessage()) }

If I understand the use-case this should work.