Is the `isActive` check here necessary to make sur...
# coroutines
j
Is the
isActive
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
Copy code
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
            // ...
        }
    }
}
e
you can call
_liveData.postData(data)
from any thread
j
@ephemient I’ve omitted some code. I want to switch to main thread because I use a variable
isFetched
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.
Copy code
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) cancelled
s
I don't see much use in calling
isActive
. 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.
👍 3