Pull to refresh
4
0
Bulat Mukhutdinov @Biggy_B

Android Dev

Send message

Suspending over blocking

Reading time9 min
Views2.8K

This article aims to show how to use Kotlin Coroutines and remove Reaxtive eXtensions (Rx).


Benefits


To start let's consider four benefits of Coroutines over Rx:


Suspending over Blocking


To run non-blocking code using Rx you'd write something like this:


Observable.interval(1, TimeUnit.SECONDS)
    .subscribe {
        textView.text = "$it seconds have passed"
    }

Which is effectively creating a new thread. Threads are heavy objects in terms of memory and performance.


Both are critical in the mobile development world.


You can achieve the same behavior using the following snippet:


launch {
    var i = 0
    while (true){
        textView.text = "${it++} seconds have passed"
        delay(1000)
    }
}

Essentially, Coroutines are light-weight threads but we don't create any real thread.
Here we are using non-blocking delay() function, which is a special suspending function that does not block a thread but suspends the Coroutine.

Read more →
Total votes 7: ↑6 and ↓1+5
Comments3

Information

Rating
Does not participate
Registered
Activity