RxJava与Kotlin的花括号和普通括号之间有什么区别

bla*_*her 14 android kotlin rx-java2

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

someMethodThatReturnsCompletable()
    .andThen(anotherMethodThatReturnsACompletable())
    .subscribe(...)
Run Code Online (Sandbox Code Playgroud)

但以下不起作用:

someMethodThatReturnsCompletable()
    .andThen { anotherMethodThatReturnsACompletable() }
    .subscribe(...)
Run Code Online (Sandbox Code Playgroud)

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

Bak*_*aii 7

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

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

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

lock (lock) {
    sharedResource.operation()
}
Run Code Online (Sandbox Code Playgroud)

由于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)
Run Code Online (Sandbox Code Playgroud)

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

andThen( CompletableSource {
    //implementations
})
Run Code Online (Sandbox Code Playgroud)


erl*_*man 6

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

{}-> 你正在它们里面执行一些东西。即表达


cha*_*l03 5

您可能知道,在 Java 中()括号用于传递参数,{}大括号用于方法主体,也代表 lambda 表达式的主体。

所以让我们比较一下:

  1. .andThen(anotherMethodThatReturnsACompletable()): 这里 andThen() 方法接受Completableso andThen 将保存对anotherMethodThatReturnsACompletable()方法返回的 Completable 的引用以供稍后订阅。

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

希望能帮助到你。