Coroutine-Aware ViewModel
Have you desired control over the execution context of your multi-threaded environment? Have you encountered challenges emanating from multiple spawned threads not being managed adequately?
One can effectively manage asynchronous computations in a cooperative pattern by adopting coroutines. A coroutine is a method that executes for a certain period, suspends, and permits other coroutines to run. A CoroutineScope
binds all the launched coroutines to a CoroutineContext
. A CoroutineContext is an indexed type-safe heterogeneous map encompassing CoroutineContext.Key
to CoroutineContext.Element
pairs.
The ViewModel
is always bound to the lifecycle of an activity or a fragment. It aids in storing and managing UI-related data in a lifecycle-aware approach. We can supervise over coroutines by composing ViewModels that confine them to a particular CoroutineScope.
job: Job
operates as the parent job of every coroutine launched using CustomCoroutineScope
. We can supervise over child coroutines by supplying a SupervisorJob
; permitting child coroutines to fail independently.
A coroutine launched using CustomCoroutineScope
will run on a shared pool of background threads as the Default
dispatcher is supplied above.
We can override the execution context behaviour by supplying an alternative CoroutineContext
to launch
.
We can cancel our child coroutines when the ViewModel is about to be destroyed. The coroutineContext.cancel()
cancels the parent job which in turn leads to cancellation of child coroutines.
What if we desire blocks of code that complete their execution in any scenario?
We can override the parent by supplying a NonCancellable
job to prevent cancellation.