Skip to main content

Module runtime

Module runtime 

Source
Expand description

Runtime for executing TUI applications.

This module provides the Runtime type that manages the application lifecycle based on The Elm Architecture (TEA). It coordinates message processing, command execution, subscription management, and rendering.

§Overview

The runtime follows The Elm Architecture pattern:

  1. Initialization: Create a Runtime with initial flags and frame rate
  2. Event Loop: Process messages via Application::update, render via Application::view
  3. Commands: Execute asynchronous operations that produce messages
  4. Subscriptions: Receive external events (timers, signals, etc.)
  5. Termination: Exit cleanly when quit is requested

§Performance Optimizations

The runtime includes built-in optimizations that are transparent to applications:

  • Micro-batching: Messages arriving in quick succession (within 100μs) are batched together for processing, reducing overhead and improving responsiveness
  • Conditional Rendering: The UI is only re-rendered when the application state changes, skipping unnecessary draw operations
  • Subscription Caching: Subscriptions are only re-evaluated after a message is processed (idle frames are skipped), and the subscription manager is only updated when their IDs change, using hash-based comparison for efficiency

§Example

use color_eyre::eyre::Result;
use ratatui::Frame;
use tears::prelude::*;

struct CounterApp {
    count: i32,
}

enum Message {
    Increment,
    Quit,
}

impl Application for CounterApp {
    type Message = Message;
    type Flags = ();

    fn new(_flags: ()) -> (Self, Command<Message>) {
        (Self { count: 0 }, Command::none())
    }

    fn update(&mut self, msg: Message) -> Command<Message> {
        match msg {
            Message::Increment => {
                self.count += 1;
                Command::none()
            }
            Message::Quit => Command::effect(Action::Quit),
        }
    }

    fn view(&self, frame: &mut Frame<'_>) {
        // Render UI...
    }

    fn subscriptions(&self) -> Vec<Subscription<Message>> {
        vec![]
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    let runtime = Runtime::<CounterApp>::new((), 60);
    let mut terminal = ratatui::init();
    runtime.run(&mut terminal).await?;
    ratatui::restore();
    Ok(())
}

Structs§

Runtime
Runtime that schedules and executes TUI application operations.