blackpanther blackpanther - 1 year ago 136
Android Question

What's the difference between curly braces and normal brackets in RxJava with 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(...)


But the following does NOT work:

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


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.

Answer Source

As you probably know that in Java () brackets are used for passing parameters and {} braces are used for method body and also represents the body of lambda expression.

So lets compare:

  1. .andThen(anotherMethodThatReturnsACompletable()) : here andThen() method accepts Completable so andThen will save reference to the completable returned by anotherMethodThatReturnsACompletable() method to subscribe later.

  2. .andThen { anotherMethodThatReturnsACompletable() } : This passes lambda expression to andThen method. Here anotherMethodThatReturnsACompletable() is not invoked at the time of passing the lambda. anotherMethodThatReturnsACompletable() will be called when lambda function is invoked in andThen method.

Hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download