Use SupervisorJob in viewModelscope
Test: testJobIsSuperVisor
Change-Id: I473e3e901d1aec9cac5a42f18b7c70793aa6c1d0
diff --git a/lifecycle/viewmodel/ktx/src/androidTest/java/androidx/lifecycle/ViewModelTest.kt b/lifecycle/viewmodel/ktx/src/androidTest/java/androidx/lifecycle/ViewModelTest.kt
index 127afe77..a5e4553 100644
--- a/lifecycle/viewmodel/ktx/src/androidTest/java/androidx/lifecycle/ViewModelTest.kt
+++ b/lifecycle/viewmodel/ktx/src/androidTest/java/androidx/lifecycle/ViewModelTest.kt
@@ -18,8 +18,12 @@
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth
+import kotlinx.coroutines.async
+import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@@ -53,4 +57,21 @@
val scope3 = vm.viewModelScope
Truth.assertThat(scope3).isSameAs(scope2)
}
+
+ @Test fun testJobIsSuperVisor() {
+ val vm = object : ViewModel() {}
+ val scope = vm.viewModelScope
+ val delayingDeferred = scope.async { delay(Long.MAX_VALUE) }
+ val failingDeferred = scope.async { throw Error() }
+
+ runBlocking {
+ try {
+ failingDeferred.await()
+ Assert.fail()
+ } catch (e: Error) {
+ }
+ Truth.assertThat(delayingDeferred.isActive).isTrue()
+ delayingDeferred.cancelAndJoin()
+ }
+ }
}
\ No newline at end of file
diff --git a/lifecycle/viewmodel/ktx/src/main/java/androidx/lifecycle/ViewModel.kt b/lifecycle/viewmodel/ktx/src/main/java/androidx/lifecycle/ViewModel.kt
index 74a0f00..0d8e203 100644
--- a/lifecycle/viewmodel/ktx/src/main/java/androidx/lifecycle/ViewModel.kt
+++ b/lifecycle/viewmodel/ktx/src/main/java/androidx/lifecycle/ViewModel.kt
@@ -18,7 +18,7 @@
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import java.io.Closeable
import kotlin.coroutines.CoroutineContext
@@ -38,7 +38,7 @@
return scope
}
return setTagIfAbsent(JOB_KEY,
- CloseableCoroutineScope(Job() + Dispatchers.Main))
+ CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main))
}
internal class CloseableCoroutineScope(context: CoroutineContext) : Closeable, CoroutineScope {