Context

R3BL TUI library & suite of apps focused on developer productivity

We are working on building command line apps in Rust which have rich text user interfaces (TUI). We want to lean into the terminal as a place of productivity, and build all kinds of awesome apps for it.

  1. 🔮 Instead of just building one app, we are building a library to enable any kind of rich TUI development w/ a twist: taking concepts that work really well for the frontend mobile and web development world and re-imagining them for TUI & Rust.

  2. 🌎 We are building apps to enhance developer productivity & workflows.

r3bl_redux

redux

Store is thread safe and asynchronous (using Tokio). You have to implement async traits in order to use it, by defining your own reducer, subscriber, and middleware trait objects. You also have to supply the Tokio runtime, this library will not create its own runtime. However, for best results, it is best to use the multithreaded Tokio runtime.

Once you setup your Redux store w/ your reducer, subscriber, and middleware, you can use it by calling spawn_dispatch_action!( store, action ). This kicks off a parallel Tokio task that will run the middleware functions, reducer functions, and finally the subscriber functions. So this will not block the thread of whatever code you call this from. The spawn_dispatch_action!() macro itself is not async. So you can call it from non async code, however you still have to provide a Tokio executor / runtime, without which you will get a panic when spawn_dispatch_action!() is called.

Middlewares

Your middleware (async trait implementations) will be run concurrently or in parallel via Tokio tasks. You get to choose which async trait to implement to do one or the other. And regardless of which kind you implement the Action that is optionally returned will be dispatched to the Redux store at the end of execution of all the middlewares (for that particular spawn_dispatch_action!() call).

  1. AsyncMiddlewareSpawns<State, Action> - Your middleware has to use tokio::spawn to run async blocks in a separate thread and return a JoinHandle that contains an Option<Action>. A macro fire_and_forget! is provided so that you can easily spawn parallel blocks of code in your async functions. These are added to the store via a call to add_middleware_spawns(...).

  2. AsyncMiddleware<State, Action> - They are will all be run together concurrently using futures::join_all(). These are added to the store via a call to add_middleware(...).

Subscribers

The subscribers will be run asynchronously via Tokio tasks. They are all run together concurrently but not in parallel, using futures::join_all().

Reducers

The reducer functions are also are async functions that are run in the tokio runtime. They're also run one after another in the order in which they're added.

Any functions or blocks that you write which uses the Redux library will have to be marked async as well. And you will have to spawn the Tokio runtime by using the #[tokio::main] macro. If you use the default runtime then Tokio will use multiple threads and its task stealing implementation to give you parallel and concurrent behavior. You can also use the single threaded runtime; its really up to you.

  1. To create middleware you have to implement the AsyncMiddleware<S,A> trait or AsyncMiddlewareSpawns<S,A> trait. Please read the AsyncMiddleware docs for examples of both. The run() method is passed two arguments: the State and the Action.

    1. For AsyncMiddlewareSpawns<S,A> in your run() implementation you have to use the fire_and_forget! macro to surround your code. And this will return a JoinHandle<Option<A>>.
    2. For AsyncMiddleware<S,A> in your run() implementation you just have to return an Option<A>>.
  2. To create reducers you have to implement the AsyncReducer trait.

  3. To create subscribers you have to implement the AsyncSubscriber trait.

Summary

Here's the gist of how to make & use one of these:

  1. Create a struct. Make it derive Default. Or you can add your own properties / fields to this struct, and construct it yourself, or even provide a constructor function.
  2. Implement the AsyncMiddleware, AsyncMiddlewareSpawns, AsyncReducer, or AsyncSubscriber trait on your struct.
  3. Register this struct w/ the store using one of the add_middleware(), add_middleware_spawns(), add_reducer(), or add_subscriber() methods. You can register as many of these as you like.

Examples

💡 There are lots of examples in the tests for this library and in this CLI application built using it.

Here's an example of how to use it. Let's start w/ the import statements.

rust /// Imports. use async_trait::async_trait; use r3bl_rs_utils::redux::{ AsyncMiddlewareSpawns, AsyncMiddleware, AsyncReducer, AsyncSubscriber, Store, StoreStateMachine, }; use std::sync::{Arc, Mutex}; use tokio::sync::RwLock;

  1. Make sure to have the tokio and async-trait crates installed as well as r3bl_rs_utils in your Cargo.toml file.
  2. Here's an example Cargo.toml.

Let's say we have the following action enum, and state struct.

```rust /// Action enum.

[derive(Debug, PartialEq, Eq, Clone)]

pub enum Action { Add(i32, i32), AddPop(i32), Clear, MiddlewareCreateClearAction, Noop, }

impl Default for Action { fn default() -> Self { Action::Noop } }

/// State.

[derive(Clone, Default, PartialEq, Debug)]

pub struct State { pub stack: Vec, } ```

Here's an example of the reducer function.

```rust /// Reducer function (pure).

[derive(Default)]

struct MyReducer;

[async_trait]

impl AsyncReducer for MyReducer { async fn run( &self, action: &Action, state: &State, ) -> State { match action { Action::Add(a, b) => { let sum = a + b; State { stack: vec![sum] } } Action::AddPop(a) => { let sum = a + state.stack[0]; State { stack: vec![sum] } } Action::Clear => State { stack: vec![] }, _ => state.clone(), } } } ```

Here's an example of an async subscriber function (which are run in parallel after an action is dispatched). The following example uses a lambda that captures a shared object. This is a pretty common pattern that you might encounter when creating subscribers that share state in your enclosing block or scope.

```rust /// This shared object is used to collect results from the subscriber /// function & test it later. let shared_object = Arc::new(Mutex::new(Vec::::new()));

[derive(Default)]

struct MySubscriber { pub sharedobjectref: Arc>>, }

[async_trait]

impl AsyncSubscriber for MySubscriber { async fn run( &self, state: State, ) { let mut stack = self .sharedobjectref .lock() .unwrap(); if !state.stack.is_empty() { stack.push(state.stack[0]); } } }

let mysubscriber = MySubscriber { sharedobjectref: sharedobject_ref.clone(), }; ```

Here are two types of async middleware functions. One that returns an action (which will get dispatched once this middleware returns), and another that doesn't return anything (like a logger middleware that just dumps the current action to the console). Note that both these functions share the shared_object reference from above.

```rust /// This shared object is used to collect results from the subscriber /// function & test it later.

[derive(Default)]

struct MwExampleNoSpawn { pub sharedobjectref: Arc>>, }

[async_trait]

impl AsyncMiddleware for MwExampleNoSpawn { async fn run( &self, action: Action, storeref: Arc>>, ) { let mut stack = self .sharedobjectref .lock() .unwrap(); match action { Action::MwExampleNoSpawnAdd(, ) => stack.push(-1), Action::MwExampleNoSpawnAddPop() => stack.push(-2), Action::MwExampleNoSpawnClear => stack.push(-3), _ => {} } None } }

let mwexamplenospawn = MwExampleNoSpawn { sharedobjectref: sharedobject_ref.clone(), };

/// This shared object is used to collect results from the subscriber /// function & test it later.

[derive(Default)]

struct MwExampleSpawns { pub sharedobjectref: Arc>>, }

[async_trait]

impl AsyncMiddlewareSpawns for MwExampleSpawns { async fn run( &self, action: Action, storeref: Arc>>, ) -> JoinHandle> { fireandforget!( { let mut stack = self .sharedobjectref .lock() .unwrap(); match action { Action::MwExampleSpawnsModifySharedObjectResetState => { sharedvec.push(-4); return Action::Reset.into(); } _ => {} } None } ); } }

let mwexamplespawns = MwExampleSpawns { sharedobjectref: sharedobjectref.clone(), }; ```

Here's how you can setup a store with the above reducer, middleware, and subscriber functions.

rust // Setup store. let mut store = Store::<State, Action>::default(); store .add_reducer(MyReducer::new()) // Note the use of `::new()` here. .await .add_subscriber(Box::new( // We aren't using `::new()` here my_subscriber, // because the struct has properties. )) .await .add_middleware_spawns(Box::new( // We aren't using `::new()` here mw_example_spawns, // because the struct has properties. )) .await .add_middleware(Box::new( // We aren't using `::new()` here mw_example_no_spawn, // because the struct has properties. )) .await;

Finally here's an example of how to dispatch an action in a test. You can dispatch actions in parallel using spawn_dispatch_action!() which is "fire and forget" meaning that the caller won't block or wait for the spawn_dispatch_action!() to return.

``rust // Test reducer and subscriber by dispatchingAdd,AddPop,Clear` actions in parallel. spawndispatchaction!( store, Action::Add(1, 2) ); asserteq!(sharedobject.lock().unwrap().pop(), Some(3));

spawndispatchaction!( store, Action::AddPop(1) ); asserteq!(sharedobject.lock().unwrap().pop(), Some(4));

spawndispatchaction!( store, Action::Clear ); asserteq!(store.getstate().stack.len(), 0); ```

Other crates that depend on this

This crate is a dependency of the following crates:

  1. r3bl_rs_utils crates (the "main" library)

Issues, comments, feedback, and PRs

Please report any issues to the issue tracker. And if you have any feature requests, feel free to add them there too 👍.