5

I'm trying to use kotlin M12 in android project and during the work I got this piece of code subscribe({onSuccess(it)}, {onFailure(it)})

AppObservable.bindActivity(this, api.get(id)).subscribe({onSuccess(it)}, {onFailure(it)})

fun onSuccess(str: String) {}

fun onFailure(tr: Throwable) {}

This is not so bad, but I think it would/should be better. How can I improve it?

4

1 回答 1

6

首先,创建一个辅助扩展方法,如下所示:

fun<T, R> Observable<T>.subscribe(
        receiver: R,
        onSuccess: R.(T) -> Unit, 
        onFailure: R.(Throwable) -> Unit) {
    subscribe({ receiver.onSuccess(it) }, { receiver.onFailure(it) })
}

现在您可以像这样使用新方法:

AppObservable.bindActivity(this, api.get(id)).subscribe(this, ::onSuccess, ::onFailure)

::操作员创建一个方法引用。一旦KT-6947得到解决,我们可以省略 helper 方法并subscribe(this::onSuccess, this::onFailure)直接编写。这在 Java 8 中已经成为可能。

为了解决这个问题,我们可以选择实现以下将接收器绑定到扩展方法的辅助方法:

fun <T, R, E> T.bind(reference: T.(R) -> E): (R) -> E = { this.reference(it) }

并像这样使用它:

AppObservable.bindActivity(this, api.get(id)).subscribe(bind(Foo::onSuccess), bind(Foo::onFailure))

但这并不比您最初的解决方案更优雅。

编辑1:

你的语法::onSuccess暂时被禁止,所以你必须使用 'Foo::onSuccess'Foo你的类名在哪里。

编辑2:

通过声明与

operator fun <T, R, E> T.plus(reference: T.(R) -> E): (R) -> E = { this.reference(it) }

然后你可以像这样使用它:

AppObservable.bindActivity(this, api.get(id)).subscribe(this + Foo::onSuccess, this + Foo::onFailure)
于 2015-07-01T09:26:54.277 回答