带有 Kotlin 的 RxJava 中的花括号和普通括号有什么区别

What's the difference between curly braces and normal brackets in RxJava with Kotlin

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

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

但以下内容不起作用:

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

请注意链的 andThen() 部分与花括号的区别。我不明白两者之间的区别是什么。我看过一些文章,但不幸的是,我仍然难以理解这种细微差别。

.andThen(anotherMethodThatReturnsACompletable())表示anotherMethodThatReturnsACompletable()的结果会传给andThen()

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

第一个代码段执行 anotherMethodThatReturnsACompletable() 并将 return 值传递给 andThen(),其中接受 Completable 作为参数。

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

In Kotlin, there is a convention that if the last parameter to a function is a function, and you're passing a lambda expression as the corresponding argument, you can specify it outside of parentheses:

lock (lock) {
    sharedResource.operation()
}

因为 Kotlin 支持 SAM conversion

This means that Kotlin function literals can be automatically converted into implementations of Java interfaces with a single non-default method, as long as the parameter types of the interface method match the parameter types of the Kotlin function.

回顾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
})

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

所以让我们比较一下:

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

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

希望对您有所帮助。

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

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