RxJava和Kotlin的花括号和正常括号有什么区别?
我不明白使用RxJava时,大括号和Kotlin中的正常括号之间的真正区别。 例如,我有以下代码,它按预期工作:
someMethodThatReturnsCompletable() .andThen(anotherMethodThatReturnsACompletable()) .subscribe(...)
但以下不起作用:
someMethodThatReturnsCompletable() .andThen { anotherMethodThatReturnsACompletable() } .subscribe(...)
用大括号注意链中的andThen()
部分的区别。 我不明白这两者之间的区别是什么。 我已经看了一些文章,但不幸的是,我仍然很难理解这种微妙的差异。
第一个代码段执行anotherMethodThatReturnsACompletable()
并将返回值传递给andThen()
,其中Completable
被接受为参数。
在第二个代码段中,您正在将函数文字写成lambdaexpression式 。 它将type () -> Unit
的函数传递给andThen()
,它也是一个有效的语句,但是lambda中的代码可能不会被调用。
在Kotlin中,有一个约定,如果函数的最后一个参数是一个函数,并且将一个lambdaexpression式作为相应的parameter passing,则可以在括号外指定它:
lock (lock) { sharedResource.operation() }
由于Kotlin支持SAM转换 ,
这意味着只要接口方法的参数types与Kotlin函数的参数types匹配,Kotlin函数文本就可以用一个非默认方法自动转换为Java接口的实现。
回顾Completable
,有几个重载和andThen()
函数:
andThen(CompletableSource next) andThen(MaybeSource next) andThen(ObservableSource next) andThen(org.reactivestreams.Publisher next) andThen(SingleSource next)
在这里您可以通过调用以下方式指定SAMtypes:
andThen( CompletableSource { //implementations })
正如你可能知道在Java ()
中使用括号来传递参数, {}
括号用于方法体,也表示lambdaexpression式的主体。
所以让我们来比较
-
.andThen(anotherMethodThatReturnsACompletable())
:这里和Then()方法接受Completable
,然后将保存对anotherMethodThatReturnsACompletable()方法返回的Completable
引用。 -
.andThen { anotherMethodThatReturnsACompletable() }
:这将lambdaexpression式传递给andThen方法。 这里anotherMethodThatReturnsACompletable()
在传递lambda时不会被调用。 在andThen方法中调用lambda函数时,将调用anotherMethodThatReturnsACompletableanotherMethodThatReturnsACompletable()
。
希望能帮助到你。
.andThen(anotherMethodThatReturnsACompletable())
意味着.andThen(anotherMethodThatReturnsACompletable())
的结果将传递给andThen()
.andThen { anotherMethodThatReturnsACompletable() }
意味着执行andThen()
的lambda将被传递给andThen()
()
– >你在里面传递一些东西,比如函数参数
{}
– >你正在执行里面的东西。 即expression