blackpanther blackpanther - 6 months ago 65
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:


But the following does NOT work:

.andThen { anotherMethodThatReturnsACompletable() }

Note the difference in the
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