Hi all! What is the difference between Job and Sup...
# coroutines
a
Hi all! What is the difference between Job and SupervisorJob in case of Exception Handling?
Copy code
class Presenter() : CoroutineScope {
        private val job = Job()

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

        override fun onDestroy() {
            job.cancel()
        }

        fun loadData() {
            launch {
                try {
                    //loadData().async()
                } catch (e: Exception) {
                    //handle exception
                }
            }

        }
    }
Copy code
class Presenter() : CoroutineScope {
        private val job = SupervisorJob()

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

        override fun onDestroy() {
            job.cancel()
        }

        fun loadData() {
            launch {
                try {
                    //loadData().async()
                } catch (e: Exception) {
                    //handle exception
                }
            }

        }
    }
g
Did you read docs of SupervisorJob?
a
Yes, looks like second example is the way to go in most cases.
g
What is the actual difference between SupervisorJob() and CoroutineScope constructor?
This question doesn’t make make sense, Job and Scope are different things
In your case difference caused by different work of Job and SupervisorJob (and by default scope uses Job)
What is not clear for you? Why Job works like that? Or why do you have this exception?
a
@gildor The only part that is still unclear for me is why the following solution should work? use the following shortcut via
CoroutineScope
constructor:
Copy code
class UserViewModel: ViewModel, CoroutineScope by CoroutineScope(Dispatchers.Default) {
    override fun onCleared() {
        super.onCleared()
        cancel()
    }
}
The working solution is to create new Job(), after exception is caught:
Copy code
CoroutineExceptionHandler { _, throwable ->
        //onError(throwable)
        job = Job()
    }
g
job = Job() - this looks wrong
why the following solution should work?
Could you elaborate, what exactly means “should work”, does it work for you?
It’s pretty clear in your original example
but I don’t understand what you want to do in your last message
a
The question is related to Roman Elizarov answer: https://github.com/Kotlin/kotlinx.coroutines/issues/996#issuecomment-468890079 SupervisorJob() works great but the second solution does not.
g
But this not related to CoroutineExceptionHandler
a
ok - now i got it 🙂
thanks!
g
or use the following shortcut via CoroutineScope constructor:
I actually not sure what Romain means by this, this is exactly the same as version above, just more concise
but SupervisorJob is definitely related
a
Yeap, SupervisorJob works great!