maycoon_core/app/
context.rs

1use crate::app::update::{Update, UpdateManager};
2use crate::signal::Signal;
3use std::sync::Arc;
4
5/// The application context for managing the application lifecycle.
6#[derive(Clone, Debug)]
7pub struct AppContext {
8    update: UpdateManager,
9}
10
11impl AppContext {
12    /// Create a new application context using the given [UpdateManager].
13    pub fn new(update: UpdateManager) -> Self {
14        Self { update }
15    }
16
17    /// Get the [UpdateManager] of this application context.
18    pub fn update(&self) -> UpdateManager {
19        self.update.clone()
20    }
21
22    /// Hook the given [Signal] to the [UpdateManager] of this application.
23    ///
24    /// This makes the signal reactive, so it will notify the renderer when the inner value changes.
25    pub fn hook_signal<T: 'static, S: Signal<T>>(&self, signal: &mut S) {
26        let update = self.update();
27
28        signal.listen(Box::new(move |_| {
29            update.insert(Update::EVAL);
30        }));
31    }
32
33    /// Hook the given [Signal] to the [UpdateManager] of this application and return it inside an [Arc].
34    ///
35    /// See [AppContext::hook_signal] for more.
36    pub fn use_signal<T: 'static, S: Signal<T>>(&self, mut signal: S) -> Arc<S> {
37        self.hook_signal(&mut signal);
38
39        Arc::new(signal)
40    }
41}