Module mogwai::relay

source ·
Expand description

Bundling view updates and events.

Views are sometimes very complex. Many times we either have to manage a large number of channels or a small number of channels that send messages with many enum variants. Both cases can become overwhelming.

To help with this situation mogwai >= 0.5.2 has introduced the concept of view “relays”. A view relay is an object that uses inputs and outputs to manage communicating updates and events to and from a view. Instead of having to know the intricacies of a number of different channels and their operating behavior, the library user creates a struct that defines inputs and outputs and uses those to construct a ViewBuilder. Updates to the view are then made by interacting with the relay struct asyncronously from within a logic loop.

Example

use mogwai::prelude::*;

#[derive(Default)]
struct ClickyDiv {
    click: Output<()>,
    text: Input<String>,
}

impl TryFrom<ClickyDiv> for ViewBuilder {
    type Error = anyhow::Error;

    fn try_from(mut cd: ClickyDiv) -> anyhow::Result<ViewBuilder> {
        Ok(ViewBuilder::element("div")
            .with_event("click", "myself", cd.click.sink().contra_map(|_: AnyEvent| ()))
            .append(
                ("Hi", cd.text.stream().ok_or_else(|| anyhow::anyhow!("already used text stream"))?)
            )
            .with_task(async move {
                let mut clicks = 0;
                while let Some(()) = cd.click.get().await {
                    clicks += 1;
                    cd.text
                        .set(if clicks == 1 {
                            "1 click.".to_string()
                        } else {
                            format!("{} clicks.", clicks)
                        })
                        .await
                        .unwrap()
                }
            })
        )
    }
}

let cd = ClickyDiv::default();
let builder = ViewBuilder::try_from(cd).unwrap();

Structs

  • An input that fans input values to many consumers.
  • An input to a view.
  • An event output from a view.