https://kotlinlang.org logo
Title
j

Johnny

10/17/2021, 12:09 AM
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
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

ephemient

10/17/2021, 12:44 AM
you can call
_liveData.postData(data)
from any thread
j

Johnny

10/17/2021, 12:54 AM
@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.
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

streetsofboston

10/17/2021, 3:02 AM
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