NewtoKotlin
01/24/2024, 2:18 AM@Component
class RiskAssertionFeedbackHandler(
) {
companion object {
}
fun sendFeedback (authZResponse: AuthZResponse){
val customScopeLocal = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO> + MDCContext())
customScopeLocal.launch {
when {
isOperationSupportedForAuthBlock(authZResponse, reason!!, operationMethodName!!) -> {
authBlockedFeedbackHandler.recordAuthBlocked(authZResponse, reason , operationMethodName)
}
}
}
}
fun sendFeedback(operationMethodName: String, feedbackTransaction: FraudTransaction) {
ThreadContextLocal.addAllAttributesToMDC()
val customScope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO> + MDCContext())
customScope.launch {
when (feedbackTransaction) {
FraudTransaction.AUTH_BLOCKED -> authFailedFeedbackHandler.recordAuthFailed(operationMethodName)
FraudTransaction.UAF_REG_PASS -> uafRegPassFeedbackHandler.recordUAFRegPass(operationMethodName)
FraudTransaction.UAF_REG_FAILED -> uafRegFailedFeedbackHandler.recordUAFRegFailed(operationMethodName)
}
}
}
Is this efficient way to launch coroutines ? I read that CoroutineScope is also same as GlobalLaunch and not good for production.ephemient
01/24/2024, 3:43 AMephemient
01/24/2024, 3:44 AMNewtoKotlin
01/24/2024, 4:12 AMNewtoKotlin
01/24/2024, 4:19 AMNewtoKotlin
01/24/2024, 4:36 AMNewtoKotlin
01/24/2024, 4:37 AMNewtoKotlin
01/31/2024, 8:59 AMNewtoKotlin
01/31/2024, 8:59 AMross_a
01/31/2024, 10:10 AM@Configuration
class MyConfiguration {
@Qualifier("default")
@Bean
fun defaultDispatcher() = Dispatchers.Default
}
@Component
class MyComponent(
@Qualifier("default") private val defaultDispatcher: CoroutineDispatcher,
) {
private val backgroundScope = CoroutineScope(
defaultDispatcher +
SupervisorJob() +
CoroutineExceptionHandler { coroutineContext, throwable ->
// logging
}
)
fun launchBackgroundWork(): Job {
return backgroundScope.launch {
// Background work
}
}
fun launchOtherBackgroundWork(): Job {
return backgroundScope.launch {
// Background work
}
}
@PreDestroy
fun destroy() {
backgroundScope.cancel()
}
}
ross_a
01/31/2024, 10:13 AM@PreDestroy
to ensure the scope is bound to the bean's lifecycle (particularly useful if your Spring application does context reloads).
I often return Job when launching background work so that the calling method can optionally choose to wait for completion with join, but this is optionalNewtoKotlin
01/31/2024, 10:15 AMNewtoKotlin
01/31/2024, 10:16 AMross_a
01/31/2024, 10:17 AMfun launchOtherBackgroundWork(): Job {
return backgroundScope.launch(MDCContext()) {
// Background work
}
}
NewtoKotlin
01/31/2024, 10:18 AMross_a
01/31/2024, 10:19 AMNewtoKotlin
01/31/2024, 10:27 AMross_a
01/31/2024, 10:37 AMSupervisorJob()
ross_a
01/31/2024, 10:38 AM