Skip to content

Commit

Permalink
jobs are cancelled properly
Browse files Browse the repository at this point in the history
  • Loading branch information
Shivam Dhuria committed Jun 8, 2020
1 parent 05e3987 commit 0e8c396
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
6 changes: 6 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,10 @@ dependencies {
//Glide
kapt "com.github.bumptech.glide:compiler:$glide_version"
implementation "com.github.bumptech.glide:glide:$glide_version"

//testing
testImplementation 'junit:junit:4.12'
testImplementation "org.mockito:mockito-core:3.3.3"
testImplementation 'androidx.arch.core:core-testing:2.1.0'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.4'
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ class MainActivityViewModel @Inject constructor(private val mainActivityReposito
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + parentJob

val scope = Dispatchers.Main

val dogList: LiveData<List<Dog>>
get() = _dogList
val snackbar: LiveData<String?>
Expand All @@ -38,20 +40,21 @@ class MainActivityViewModel @Inject constructor(private val mainActivityReposito
}

fun loadTopTwoDogsAsync() {
launch {
viewModelScope.launch {
logCoroutine("loadTopTwoDogsAsync", coroutineContext)
val list = runCatching { mainActivityRepository.getTopTwoDogsAsync() }
list.onSuccess {
_topDogsAsync.value = it.value
}.onFailure {
_snackbar.value = it.message.toString()
_snackbar.value = "loadTopTwoDogsAsync() " + it.message.toString()
}
}
}

fun loadDogListSynchronously() {
_dogList.value = emptyList()
parentJob.cancelChildren()
_dogList.value = emptyList()
launch {
_status.value = "Loading..."
val start = System.currentTimeMillis()
Expand All @@ -61,7 +64,7 @@ class MainActivityViewModel @Inject constructor(private val mainActivityReposito
_dogList.value = it.value
}.onFailure {
_status.value = "Failed."
_snackbar.value = it.message.toString()
_snackbar.value = "loadDogListSynchronously() " + it.message.toString()
}
}
}
Expand All @@ -78,7 +81,7 @@ class MainActivityViewModel @Inject constructor(private val mainActivityReposito
_dogList.value = it.value
}.onFailure {
_status.value = "Failed."
_snackbar.value = it.message.toString()
_snackbar.value = "loadDogListAsynchronously() " + it.message.toString()
}
}
}
Expand Down

0 comments on commit 0e8c396

Please sign in to comment.