HotReloadScope class and staticHotReloadScope object provide a way to register hooks that execute after hot reload events, outside of composable context.
HotReloadScope
HotReloadScope is an abstract class that provides methods for interacting with hot reload functionality.
invokeAfterHotReload()
Registers an action to be executed after a hot reload.A lambda function called after each hot reload on the main thread. This action should not throw exceptions. If an exception occurs, it will be re-thrown at the end of the main thread’s dispatch queue.
An
AutoCloseable handle that can be used to unregister the hook. Call close() on the returned object when you no longer want the action to be invoked after reloads.Timing Guarantees
The registered action is called:- After changed classes have been reloaded
- After the heap has been migrated to new class versions
- After changed static fields have been re-initialized
- Before the next frame is rendered
Exception Handling
Theaction lambda should not throw exceptions. However, if an exception does occur:
- The exception will be caught
- It will be re-thrown at the end of the main thread’s dispatch queue
- Other reload hooks will still execute
Example
staticHotReloadScope
A static singleton instance ofHotReloadScope for registering reload hooks from non-composable code.
When to Use
UsestaticHotReloadScope when:
- You need to register reload hooks from non-composable code
- You’re managing long-lived objects that need to react to reloads
- You have control over the lifecycle and can guarantee cleanup
When NOT to Use
AvoidstaticHotReloadScope when:
- You’re in a composable function (use
AfterHotReloadEffectinstead) - You can’t guarantee the hook will be cleaned up
- The lifecycle is unclear or complex
Complete Example
Here’s a complete example showing proper lifecycle management:Memory Management
Best Practices
- Store the AutoCloseable: Always store the returned
AutoCloseablein a variable - Implement AutoCloseable: Make your class implement
AutoCloseableif it registers hooks - Use try-finally: Wrap usage in try-finally blocks to ensure cleanup
- Prefer AfterHotReloadEffect: In composables, use
AfterHotReloadEffectwhich handles cleanup automatically
Anti-Pattern Example
Correct Pattern
Platform Behavior
On JVM platforms with hot reload active,invokeAfterHotReload() registers a real hook with the hot reload agent.
On all other platforms (or when hot reload is not active), the implementation is a no-op:
- The
actionlambda is never called - The returned
AutoCloseable.close()does nothing - No performance overhead
Safe Alternative
Related APIs
AfterHotReloadEffect
Composable alternative with automatic cleanup
isHotReloadActive
Check if hot reload is enabled