带有Kotlin的RxJava中花括号和普通括号之间有什么区别 [英] What's the difference between curly braces and normal brackets in RxJava with Kotlin

查看:161
本文介绍了带有Kotlin的RxJava中花括号和普通括号之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不了解使用RxJava时花括号和Kotlin中普通括号之间的真正区别.例如,我有以下代码可以正常工作:

I don't understand the real difference between the curly braces and and the normal brackets in Kotlin when using RxJava. For example, I have the following code which works as expected:

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

但是以下操作无效:

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

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

Note the difference in the andThen() part of the chain with the curly braces. I can't understand what the difference between the two is. I've had a look at some articles but unfortunately I am still having difficulty in understanding this subtle difference.

推荐答案

第一个代码段执行anotherMethodThatReturnsACompletable()并将返回值传递给andThen(),其中将Completable用作参数.

The first code segment executes anotherMethodThatReturnsACompletable() and passes the return value to andThen(), where a Completable is accepted as parameter.

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

In the second code segment, you are writing a function literal as a lambda expression. It passes a function of type () -> Unit to andThen(), which it also a valid statement, but the code inside the lambda may not be called.

在Kotlin中,有一个约定,如果函数的最后一个参数是函数,并且您要传递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转换

Since Kotlin support SAM conversion,

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

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()函数:

Looking back to Completable, there are several overloaded andThen() functions:

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

在这里,您可以通过调用以下命令来指定SAM类型:

Here you can specify the SAM Type by calling:

andThen( CompletableSource {
    //implementations
})

这篇关于带有Kotlin的RxJava中花括号和普通括号之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆