Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rx Java, what's the difference between subscribe({}) vs subscribe { }?

Tags:

kotlin

rx-java

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()
            } }

vs

 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()
            } })

What's the difference between calling subscribe({}) vs subscribe { }

like image 424
sreekumar Avatar asked Jun 09 '26 12:06

sreekumar


1 Answers

With respect to RxJava there is no difference. Calling and execution stays the same. Its just a special syntax in kotlin known as trailing lambda.

In kotlin if you have a function with a lambda as last parameter then you can move that lambda out of parentheses. If the lambda is the only parameter then you can also remove the parentheses.

From the 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("...") }
like image 165
mightyWOZ Avatar answered Jun 12 '26 10:06

mightyWOZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!