|
| 1 | +# Async and Anathema |
| 2 | + |
| 3 | +Since the UI `Runtime` is blocking, spawn a secondary thread for our async |
| 4 | +runtime to run on. |
| 5 | + |
| 6 | +The `Runtime` can not move between threads as the `Value`s are not send. |
| 7 | +That's why it's easier, if access to component ids and emitters are required, to |
| 8 | +run the async code on a separate thread from the main thread. |
| 9 | + |
| 10 | +## Setting up for async |
| 11 | + |
| 12 | +A function that starts an async runtime in a new thread. |
| 13 | + |
| 14 | +By accepting a component id and an emitter it is possible to send messages into |
| 15 | +the Anathema runtime. |
| 16 | + |
| 17 | +```rust,ignore |
| 18 | +pub fn run_async(emitter: Emitter, component: ComponentId<MessageType>) { |
| 19 | + thread::spawn(move || { |
| 20 | + tokio::runtime::Builder::new_multi_thread() |
| 21 | + .enable_all() |
| 22 | + .build() |
| 23 | + .unwrap() |
| 24 | + .block_on(async move { |
| 25 | + // async code here |
| 26 | + }); |
| 27 | + }); |
| 28 | +} |
| 29 | +``` |
| 30 | + |
| 31 | +## Setup the UI |
| 32 | + |
| 33 | +Setup the Anathema runtime on the main thread, |
| 34 | +generate component ids and emitters and pass them to the async runtime via the |
| 35 | +aforementioned function. |
| 36 | + |
| 37 | +```rust,ignore |
| 38 | +use anathema::component::*; |
| 39 | +use anathema::prelude::*; |
| 40 | +
|
| 41 | +fn main() { |
| 42 | + // ----------------------------------------------------------------------------- |
| 43 | + // - Setup UI - |
| 44 | + // ----------------------------------------------------------------------------- |
| 45 | + let doc = Document::new("@index"); |
| 46 | +
|
| 47 | + let mut backend = TuiBackend::full_screen(); |
| 48 | + let mut builder = Runtime::builder(doc, &backend); |
| 49 | + |
| 50 | + let component_id = builder.default::<MyComponent>("index", "templates/index.aml").unwrap(); |
| 51 | + let emitter = builder.emitter(); |
| 52 | +
|
| 53 | + // ----------------------------------------------------------------------------- |
| 54 | + // - Setup async - |
| 55 | + // ----------------------------------------------------------------------------- |
| 56 | + run_async(emitter, component_id); |
| 57 | +
|
| 58 | + // ----------------------------------------------------------------------------- |
| 59 | + // - Start UI - |
| 60 | + // ----------------------------------------------------------------------------- |
| 61 | + builder.finish(&mut backend, |runtime, backend| runtime.run(backend)).unwrap(); |
| 62 | +} |
| 63 | +``` |
0 commit comments