Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Async_with__Kotlin_Coroutines.pdf

 Async_with__Kotlin_Coroutines.pdf

Asynchronous programming using Kotlin Coroutine in Android.

Avatar for Md. Ali Hossain

Md. Ali Hossain

July 27, 2019

Other Decks in Programming

Transcript

  1. ➢ Preemptively multitasking ➢ Managed by OS ➢ A thread

    is directly linked to the native thread in the corresponding OS ➢ It consumes a lot of memory for its stack. That’s why you cannot just create 100k threads ➢ Cooperatively multitasking ➢ Managed by a user ➢ It doesn't map on a native thread, it doesn't require context switching on a processor ➢ Coroutine in Kotlin doesn't have its own stack. So, you can create thousand of threads Thread vs Coroutines
  2. What we want? val user = fetchUserData() textView.text = user.name

    This is our dream code right? NetworkOnMainThreadException
  3. Finally working code val subscription = fetchUserData() { user ->

    //Callback textView.text = user.name } override fun onStop() { subscription.cancel() }
  4. And eventually you end up with something like this :)

    override fun onStop() { subscription1.cancel() subscription2.cancel() subscription3.cancel() subscription4.cancel() subscription5.cancel() }
  5. Solution -> Rx way... fun fetchUser() : Observable<User> {... }

    fetchUser() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { user -> textView.text = user.name }
  6. 3 solutions LiveData Observable Data Holder RxJava Observabe + Schedulers

    + Observer Coroutines Suspendable Computations
  7. What developer says…. LiveData Love it, But want a complete

    solution RxJava Powerful, highly adopted but often misused and perceived as an overkill solution to concurrency. Coroutines Seems like a great solution but there is a need for maturation of the extensions and developer feel that a steeve learning curve awaits....
  8. What are Coroutines? ➢ The first language to explore using

    coroutines was Simula in 1967. ➢ A lightweight thread that can run a computation ➢ Non blocking code ➢ Simplify asynchronous programming by replacing callbacks ➢ It can be suspended and resume at later time
  9. Coroutines are a great solution for two problems: 1. Long

    running tasks are tasks that take too long to block the main thread. 2. Main-safety allows you to ensure that any suspend function can be called from the main thread.
  10. Suspend Function • A function that can be started, paused

    and resume at a later time • Can only be called from a coroutine or from another suspending function • Can take parameters and have return types
  11. Coroutine Context • Every coroutine in Kotlin has a context

    that is represented by an instance of CoroutineContext interface. • A coroutine itself is represented by a Job. It is responsible for coroutine’s lifecycle, cancellation, and parent-child relations. • There is also an interface called CoroutineScope that consists of a sole property — val coroutineContext: CoroutineContext
  12. Coroutine Dispatchers Dispatchers.Main • Main thread on Android • Interact

    with the UI and perform light work • Calling suspend functions • Call UI functions • Updating LiveData Dispatchers.IO • Optimized for disk and network IO • off the main thread • Database • Reading/writing files • Networking Dispatchers.Default • Optimized for CPU intensive work • off the main thread • Sorting a list • Parsing JSON • DiffUtils
  13. Coroutine Builders 1. launch - builder will start a new

    coroutine that is “fire and forget” — that means it won’t return the result to the caller. 2. async - builder will start a new coroutine, and it allows you to return a result with a suspend function called await. 3. runBlocking - Runs new coroutine and blocks current thread interruptible until it’s completed
  14. Code example... scope.launch { // This block starts a new

    coroutine // "in" the scope. // It can call suspend functions fetchUser() } val deferredUser = GlobalScope.async { fetchUser() } try { val user = deferredUser.await() } catch (exception: Exception) { // Handle your exception }
  15. Retrofit with Coroutines... @GET() fun getUser(): Call<User> @GET() fun getUser():

    Observable<User> @GET() fun getUser(): Deferred<User> interface ApiService { } //From retrofit 2.6.0 @GET() suspend fun getUser(): User
  16. Coroutines in Android Repository class... override suspend fun fetchUser() {

    withContext(Dispatchers.IO) { val user = remoteDataSource.getUser().await() localDataSource.saveUser(user) } }
  17. Coroutines in Android ViewModel private var viewModelJob = Job() private

    val coroutineScope = CoroutineScope(viewModelJob + Dispatchers.Main) coroutineScope.launch { val user = repository.fetchUser() try { _userLiveData.value = user } catch (e: Exception) { _userLiveData.value = ArrayList() } }
  18. RxJava to Coroutines • if you are already using RxJava

    and it works for you, then use RxJava • if the architecture is based on reactive stream, then use RxJava • if the codebase is contains lots of Rx operator, then use RxJava • else, use coroutines
  19. Coroutines in Android Jetpack ➢ Workmanager - CoroutineWorker ➢ Retrofit

    - suspend function ➢ Room - suspend function ➢ livedata Builder - Make livedata with coroutines ➢ viewModelScope - Launch in ViewModel ➢ lifecycleScope - UI related coroutines ➢ Kotlinx-coroutines-test - Testing coroutines