• +91 9723535972
  • info@interviewmaterial.com

Kotlin Interview Questions and Answers

Question - How Kotlin coroutines are better than RxKotlin/RxJava?

Answer -

Kotlin coroutines are different from Rx. Both are designed to address a problem of asynchronous programming, however their approach to solution is very different:

  • Rx comes with a particular functional style of programming that can be implemented in virtually any programming language without support from the language itself. It works well when the problem at hand easily decomposes into a sequence of standard operators and not so well otherwise.

  • Kotlin coroutines provide a language feature that let library writers implement various asynchronous programming styles, including, but not limited to functional reactive style (Rx). With Kotlin coroutines you can also write your asynchronous code in imperative style, in promise/futures-based style, in actor-style, etc.
How Kotlin coroutines are better than RxKotlin? You just write sequential code, everything is as easy as writing synchronous code except it execute asynchronously. It's easier to grasp.

Coroutines are better to deal with resources

  • In RxJava you can assign computations to schedulers but subscribeOn() and ObserveOn()are confusing. Every coroutine is given a thread context and return to parent context. For a channel, both side (producer, consumer) execute on his own context. Coroutines are more intuitive on thread or thread pool affectation.
  • Coroutines give more control on when those computation occur. You can for example pass hand (yield), prioritize (select), parallelize (multiple producer/actor on channel) or lock resource (Mutex) for a given computation. It may not matter on server (where RxJava came first) but on resources limited environment this level of control may be required.
  • Due to it's reactive nature, backpressure doesn't fit well in RxJava. In the other end send() to channel is a suspensive function that suspend when channel capacity is reached. It's out-of-the-box backpressure given by nature. You could also offer() to channel, in which case the call never suspend but return false in case the channel is full, effectively reproducing onBackpressureDrop() from RxJava. Or you could just write your own custom backpressure logic, which won't be difficult with coroutines, especially compared to do the same with RxJava.

Comment(S)

Show all Coment

Leave a Comment




NCERT Solutions

 

Share your email for latest updates

Name:
Email:

Our partners