gpt4 book ai didi

android - 使用 Kotlin 的 RxJava 中的花括号和普通括号有什么区别

转载 作者:IT老高 更新时间:2023-10-28 13:33:21 25 4
gpt4 key购买 nike

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

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

但以下方法不起作用:

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

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

最佳答案

第一个代码段执行anotherMethodThatReturnsACompletable()并将返回值传递给 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
})

关于android - 使用 Kotlin 的 RxJava 中的花括号和普通括号有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45731647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com