

Android development with java was full with so much boilerplate code.

Thus, we are doing this operation in a coroutine started in viewModelScope.Android development is evolving rapidly. We can call await() only from a coroutine scope or a ‘suspend’ function. It means that we are waiting for its result and assigning it to the LiveData - fibonacciNumber. A Deferred encapsulates an operation that will be finished at some point in the future after its initialization.Īfter creating the Deferred object, we are calling await() on it. Since we have to return the result after calculations, we used the async coroutine builder( b). We created it using CoroutineScope and started it on a shared pool of background threads that perform CPU-intensive tasks( Dispatchers.Default). calculating the 20,000th Fibonacci number. We are doing a time-taking calculation, e.g. When the Fragment/Activity destroys, the coroutines in this scope will also cancel.Ĭlass DoggoRepository constructor( private val dao: DogsDao ) lifecycleScope - bound to the lifetime of a LifecycleOwner (Fragment/Activity).When the ViewModel clears, the coroutines in this scope will also cancel. viewModelScope - bound to the lifetime of a ViewModel.Coroutines started in this scope need to be canceled manually. CoroutineScope - helps to create a custom scope.It defines the lifecycle/lifetime of a coroutine. runBlocking - it blocks the underlying thread.async - it starts a coroutine and returns a result after completion.

It does not return any result on completion.

For this, we usually implement ‘AsyncTask’. We do some tasks on a background thread and publish the results on the UI thread. Asynchronous programming is inevitable while developing Android apps.
