ImanX
ImanX

Reputation: 816

What happen exactly Dispatcher.IO + job when define CoroutineScope?

I use Coroutine in my project and defined a class as CoroutineScope for handling Coroutines on difference Dispatchers such as IO, MAIN ... but I do not understand that this code how work and what is mechanism it?

val job = Job()

override val coroutineContext: CoroutineContext
     get() = Dispatchers.IO + job

what's mean Dispatchers.IO + job ?

Upvotes: 7

Views: 2191

Answers (1)

Amir
Amir

Reputation: 388

The advantage of using an specified job with Dispatchers.IO is that you can cancel that job any time without effecting other jobs that launched in the IO Dispatcher. You simply can call job.cancel()

for example you make a network request and while it's running somehow you find out network is down (for example from a BroadCastReciever if in android), then you can cancel that network job. but remember you always have to make a new Job if job is cancelled or completed

Upvotes: 9

Related Questions