问题 使用Kotlin在RxJava中使用花括号和普通括号之间的区别是什么


我不明白使用RxJava时花括号和Kotlin中的普通括号之间的真正区别。例如,我有以下代码按预期工作:

someMethodThatReturnsCompletable()
    .andThen(anotherMethodThatReturnsACompletable())
    .subscribe(...)

但以下不起作用:

someMethodThatReturnsCompletable()
    .andThen { anotherMethodThatReturnsACompletable() }
    .subscribe(...)

注意区别 andThen() 带花括号的链条的一部分。我无法理解两者之间的区别是什么。我看过一些文章,但不幸的是我仍然难以理解这种微妙的差异。


10465
2017-08-17 09:41


起源

我的问题不是关于行为 - 而是两个大括号之间的区别 - 在这种情况下它们是如何/为什么不同? - blackpanther


答案:


第一个代码段执行 anotherMethodThatReturnsACompletable() 并将返回值传递给 andThen(),哪里一个 Completable 被接受为参数。

在第二个代码段中,您将函数文字编写为 lambda表达式。它传递一个类型的函数 () -> Unit 至 andThen(),它也是一个有效的语句,但lambda中的代码可能不会被调用。

在Kotlin中,有一个约定,如果函数的最后一个参数是一个函数,并且您将lambda表达式作为相应的参数传递,则可以在括号外指定它:

lock (lock) {
    sharedResource.operation()
}

自Kotlin支持 SAM转换

这意味着只要接口方法的参数类型与Kotlin函数的参数类型匹配,Kotlin函数文字就可以使用单个非默认方法自动转换为Java接口的实现。

回头看 Completable,有几个超载 andThen() 功能:

andThen(CompletableSource next)
andThen(MaybeSource<T> next)
andThen(ObservableSource<T> next)
andThen(org.reactivestreams.Publisher<T> next)
andThen(SingleSource<T> next)

您可以在此处通过调用以下内容指定SAM类型:

andThen( CompletableSource {
    //implementations
})

5
2017-08-17 10:11





正如你在Java中可能知道的那样 () 括号用于传递参数和 {} 大括号用于方法体,也表示lambda表达式的主体。

所以让我们比较:

  1. .andThen(anotherMethodThatReturnsACompletable()) : 这里andThen()方法接受 Completable 所以然后将保存对返回的完成表的引用 anotherMethodThatReturnsACompletable() 以后订阅的方法。

  2. .andThen { anotherMethodThatReturnsACompletable() } :这将lambda表达式传递给andThen方法。这里 anotherMethodThatReturnsACompletable() 在传递lambda时不调用。 anotherMethodThatReturnsACompletable() 将在andThen方法中调用lambda函数时调用。

希望能帮助到你。


3
2017-08-17 10:13





.andThen(anotherMethodThatReturnsACompletable()) 意味着结果 anotherMethodThatReturnsACompletable() 将被传递给 andThen()

.andThen { anotherMethodThatReturnsACompletable() } 表示执行的lambda anotherMethodThatReturnsACompletable() 将被传递给 andThen()


1
2017-08-17 10:09





()  - >你在里面传递一些东西,即函数参数

{}  - >你正在执行它们内部的某些事情。表达


0
2017-08-17 10:35