resilient
Builds a ResilientPolicy by composing configured policies.
The policies are applied in a specific order, wrapping the execution block (block). The order of execution starts from the outermost policy and proceeds inwards.
Default Execution Order (from outer to inner):
fallbackcachecoalescetimeoutretrycircuitBreakerrateLimiterbulkheadhedgingchaos(only when ChaosConfig.enabled istrue)
This means a request will first pass through the fallback, then cache, then coalesce, and then timeout, and so on, until it reaches the core execution block. The chaos policy (when enabled) is the innermost wrapper, injecting faults or latency directly around the user block. The fallback policy is the last line of defense, catching any exceptions that bubble up through all other policies.
Example: fallback ->cache ->coalesce ->timeout ->retry ->... ->hedging ->block()
The composition order can be customized using ResilientBuilder.compositionOrder. This allows you to change the order in which policies are applied, which can be useful for specific use cases or performance tuning. Note that fallback is always positioned outermost automatically and cannot be configured, ensuring it can catch all failures from other policies.
Return
A ResilientPolicy instance that can be used to execute operations with the configured policies.
Parameters
The ResilientScope in which the policies will operate, typically tied to a coroutine scope.
A lambda with a ResilientBuilder receiver to configure the desired resilience policies.
Shorthand for building a ResilientPolicy bound to the lifecycle of this CoroutineScope.
Equivalent to:
resilient(this.asResilientScope(), block)Lifecycle contract:
When this CoroutineScope is cancelled, all internal background jobs spawned by the resulting policy (cache-cleanup, coalescing) are cancelled automatically.
Calling ResilientPolicy.close on the returned policy stops its internal jobs but does not cancel this CoroutineScope.
Important: Do not call this on a scope that has already been cancelled. The policy will be created, but its internal coroutines may throw kotlinx.coroutines.CancellationException when they attempt to start.
Example:
// In a ViewModel:
val policy = viewModelScope.resilient {
retry { maxAttempts = 3 }
cache { ttl = 60.seconds }
}Return
A ResilientPolicy whose background jobs are tied to this scope's lifecycle.
Parameters
Lambda with ResilientBuilder receiver to configure resilience policies.