For AI agents: the complete documentation index is at llms.txt. Markdown versions are available by appending .md or sending Accept: text/markdown.
Reflex Logo
Docs Logo

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) -> Any

Parameters

  • 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

Start Building Now!

run_in_thread Example

When to Use run_in_thread

Use run_in_thread when you need to:

  1. Execute CPU-bound operations that would otherwise block the event loop
  2. Call synchronous libraries that don't have async equivalents
  3. 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
Expand