gpt4 book ai didi

kotlin - Rx Java,subscribe({}) 与 subscribe { } 有什么区别?

转载 作者:行者123 更新时间:2023-12-02 11:33:57 34 4
gpt4 key购买 nike

Observable.just(10,20,30,40,50)
.subscribe { Consumer<Int>{
Log.d(TAG, "Where I'm I" + Thread.currentThread())
System.out.println("Hello boss")
Toast.makeText(baseContext.applicationContext, "Hellloo",Toast.LENGTH_SHORT).show()
} }

对比

 Observable.just(10,20,30,40,50)
.subscribe( { Consumer<Int>{
Log.d(TAG, "Where I'm I" + Thread.currentThread())
System.out.println("Hello boss")
Toast.makeText(baseContext.applicationContext, "Hellloo",Toast.LENGTH_SHORT).show()
} })

调用 subscribe({}) 与 subscribe { } 之间有什么区别

最佳答案

对于RxJava来说没有区别。调用和执行保持不变。它只是 kotlin 中的一种特殊语法,称为 trailing lambda

在 kotlin 中,如果您有一个以 lambda 作为最后一个参数的函数,那么您可以将该 lambda 移出括号。如果 lambda 是唯一参数,那么您也可以删除括号。

来自kotlin docs

Passing trailing lambdas

In Kotlin, there is a convention: if the last parameter of a function is a function, then a lambda expression passed as the corresponding argument can be placed outside the parentheses:

// Second argument of fold is of function type,
// hence we have moved the lambda out of parentheses.
val product = items.fold(1) { acc, e -> acc * e }

Such syntax is also known as trailing lambda.

If the lambda is the only argument to that call, the parentheses can be omitted entirely:

// run only takes a single argument of function type,
// hence we have omitted the parentheses.
run { println("...") }

关于kotlin - Rx Java,subscribe({}) 与 subscribe { } 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60242136/

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