Johnny
10/17/2021, 12:09 AMisActive
check here necessary to make sure the job wasn’t cancelled before running the code block? Or would coroutine handle it under the hood? Not sure how it prevents the race condition here
fetchDataJob = viewModelScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
val data = useDataUseCase.getData()
withContext(mainDispatcher) {
if (isActive) {
// code here shouldn't run if job was cancelled
// ...
}
}
}
ephemient
10/17/2021, 12:44 AM_liveData.postData(data)
from any threadJohnny
10/17/2021, 12:54 AMisFetched
to keep track if data has been fetched. Once it has, I set it to true
. I want to only handle this on the main thread to not have to do any synchronization on this object being accessed from multiple threads.
withContext(mainDispatcher) {
if (isActive) {
_liveData.value = data
isFetched = true
}
}
I just don’t want to show the result to the UI if this job is (manually) cancelledstreetsofboston
10/17/2021, 3:02 AMisActive
. This is a one-shot operation, it looks like. If the coroutine was cancelled, you'd never reach this code, in other words isActive
will always return true when called here.
The call to isActive
is more useful for loops that have blocking (not suspending!) code, since blocking code won't be cancelled/interrupted when the calling coroutine is cancelled.