I have a question about structured concurrency and...
# coroutines
c
I have a question about structured concurrency and blocking. So my goal here is to optionally trigger an action after a delay whenever a subscriber subscribes to the Flow without blocking the Flow. I also want this coroutine to cancel if the subscription to the original flow ends.
Copy code
val viewState: Flow<iewState> = viewState()
        .shareIn(viewModelScope, SharingStarted.Eagerly, 1)
        .onSubscription {
            optionallyTriggerActionAfterDelay()
        }

private suspend fun optionallyTriggerActionAfterDelay() {
    if (valueIsTrue) {
        delay(5000)
        triggerAction()
    }
}
This suspends the flow and delays the initial emission until the delay is complete. I’ve tried launching another coroutine in the same scope but it still seems to block
Copy code
private suspend fun optionallyTriggerActionAfterDelay() = coroutineScope {
    launch {
        if (valueIsTrue) {
            delay(5000)
            triggerAction()
        }
    }
}
And just using a different scope but this doesnt cancel
Copy code
viewModelScope.launch {
    if (valueIsTrue) {
        delay(5000)
        triggerAction()
    }
}
I could just create a separate variable that would still be tied to the view lifecycle but I am more just curious if something like this can/should be done?