Utility Functions
Reflex provides utility functions to help with common tasks in your applications.
run_in_thread
The run_in_thread function allows you to run a non-async function in a separate thread, which is useful for preventing long-running operations from blocking the UI event queue.
async def run_in_thread(func: Callable) -> AnyParameters
func: The non-async function to run in a separate thread.
Returns
- The return value of the function.
Raises
ValueError: If the function is an async function.
Usage
run_in_thread Example
When to Use run_in_thread
Use run_in_thread when you need to:
- Execute CPU-bound operations that would otherwise block the event loop
- Call synchronous libraries that don't have async equivalents
- Prevent long-running operations from blocking UI responsiveness
Example: Processing a Large File
import reflex as rx
import time
class FileProcessingState(rx.State):
progress: str = "Ready"
@rx.event(background=True)
async def process_large_file(self):
async with self:
self.progress = "Processing file..."
def process_file():
# Simulate processing a large file
time.sleep(5)
return "File processed successfully!"
# Save the result to a local variable to avoid blocking the event loop.
result = await rx.run_in_thread(process_file)
async with self:
# Then assign the local result to the state while holding the lock.
self.progress = result