Все потоки
Поиск
Написать публикацию
Обновить
4
0
Bulat Mukhutdinov @Biggy_B

Android Dev

Отправить сообщение

Suspending over blocking

Время на прочтение9 мин
Количество просмотров2.9K

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 →

Информация

В рейтинге
Не участвует
Зарегистрирован
Активность