Home > Software engineering >  What is exactly for Custom Coroutine Scope?
What is exactly for Custom Coroutine Scope?

Time:01-19

I know enough about coroutines-dispatchers-lifecycle scopes-async await. And it is obvious that all scope.launch functions returns job which we can manage coroutine lifecycle. Only thing i can not understand is custom scopes which we create with custom job.

For example:

val myJob = Job()

val customCoroutineScope= CoroutineScope(Dispatchers.IO myJob)

i thought that after these code snippet i can launch scope and manage it's lifecycle and stuff with myJob reference but it didn't work. Can someone explain me purpose and benefit of this custom scoping?

CodePudding user response:

I don't think there is any reason you'd want to pass a regular Job to the CoroutineScope constructor. If you're going to pass a Job, it should be one created using SupervisorJob(). The point of passing a SupervisorJob is so the coroutines launched by your CoroutineScope can fail independently from one another instead of any individual failure causing the cancellation of all jobs in the CoroutineScope.

There's not much reason to hold a reference to your SupervisorJob and using that to manage your CoroutineScope. Just manage your CoroutineScope from your CoroutineScope reference.

The purpose of creating a custom scope instead of using a built-in scope like lifecycleScope, viewModelScope, or GlobalScope is for situations where you want to control the lifetime of some coroutines that are not tied directly to the lifecycle of a Lifecycle object (activity or fragment) or a ViewModel.

CodePudding user response:

Kotlin coroutines are still a relatively fresh feature and they saw a lot of evolution in the years 2017-2019. For this reason there's a lot of content floating around the web that refers to patterns that used to be best practices, but are now outdated. Creating your own Job instance to put it in a scope is a good example of that. At the time structured concurrency and scopes were first introduced, there was still no support in the Android libraries for them, so this was the best way to do it.

Today, this approach would only be needed for some special-case lifecycles.

I'd also note that a scope is nothing you "launch", it's just a simple data object that wraps an instance of CoroutineScope, and its purpose is to make it easy to build a coroutine hierarchy because it's the receiver of the coroutine builder functions.

Also, when you create a CoroutineScope without including a Job explicitly, an instance is added to it automatically.

  •  Tags:  
  • Related