Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
manuelvicnt / MyViewModel.kt
Created March 21, 2019 08:11
Testing viewModelScope
class MyViewModel(dependency: ExternalDependency) : ViewModel() {
fun run() {
viewModelScope.launch {
dependency.doStuff()
}
}
}
class MyViewModelTest {
class MainViewModelUnitTest {
@get:Rule
var coroutinesTestRule = CoroutinesTestRule()
@Test
fun test() {
...
}
}
@ExperimentalCoroutinesApi
class CoroutinesTestRule(
val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
) : TestWatcher() {
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(testDispatcher)
}
internal class CloseableCoroutineScope(
context: CoroutineContext
) : Closeable, CoroutineScope {
override val coroutineContext: CoroutineContext = context
override fun close() {
coroutineContext.cancel()
}
}
@MainThread
final void clear() {
mCleared = true;
// Since clear() is final, this method is still called on mock
// objects and in those cases, mBagOfTags is null. It'll always
// be empty though because setTagIfAbsent and getTag are not
// final so we can skip clearing it
if (mBagOfTags != null) {
for (Object value : mBagOfTags.values()) {
// see comment for the similar call in setTagIfAbsent
private const val JOB_KEY = "androidx.lifecycle.ViewModelCoroutineScope.JOB_KEY"
val ViewModel.viewModelScope: CoroutineScope
get() {
val scope: CoroutineScope? = this.getTag(JOB_KEY)
if (scope != null) {
return scope
}
return setTagIfAbsent(JOB_KEY,
CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main.immediate))
class MyViewModel : ViewModel() {
/**
* Heavy operation that cannot be done in the Main Thread
*/
fun launchDataLoad() {
viewModelScope.launch {
sortList()
// Modify UI
}
class MyViewModel : ViewModel() {
/**
* This is the job for all coroutines started by this ViewModel.
* Cancelling this job will cancel all coroutines started by this ViewModel.
*/
private val viewModelJob = SupervisorJob()
/**
* This is the main scope for all coroutines launched by MainViewModel.