Skip to content

Instantly share code, notes, and snippets.

@cbeust
Last active July 2, 2024 01:59
Show Gist options
  • Save cbeust/cb6f0ef6ce6fa23929bebbf0979eeaf2 to your computer and use it in GitHub Desktop.
Save cbeust/cb6f0ef6ce6fa23929bebbf0979eeaf2 to your computer and use it in GitHub Desktop.
// Cargo.toml
// iced = { git = "https://github.com/iced-rs/iced.git", features = [ "canvas", "tokio" ] }
// futures = "0.3.30"
// tokio-stream = "0.1.15"
// crossbeam = "0.8.4"
// crossbeam-channel = "0.5.13"
use std::thread;
use std::time::Duration;
use crossbeam_channel::{Receiver, unbounded};
use iced::{Element, Subscription, Task};
use iced::application::{Title, Update};
use iced::widget::canvas::Program;
use iced::widget::text;
use crate::Message::Value;
#[derive(Clone, Debug)]
enum Message {
Tick,
Value(u8),
}
struct MyApp {
value: u8,
receiver: Receiver<u8>,
}
fn main() -> iced::Result {
let (sender, receiver) = unbounded();
thread::spawn(move || {
let mut counter = 1;
loop {
sender.send(counter).unwrap();
counter += 1;
thread::sleep(Duration::from_millis(1000))
}
});
let r = receiver.clone();
iced::application(MyTitle{}, MyApp::update, MyApp::view)
.subscription(MyApp::subscription)
.load(move || MyApp::load(r.clone()))
.run_with(move || {
MyApp {
value: 0,
receiver: receiver.clone(),
}
})
}
struct MyTitle;
impl<State> Title<State> for MyTitle {
fn title(&self, state: &State) -> String {
"My app".to_string()
}
}
impl MyApp {
fn update(&mut self, message: Message) -> impl Into<Task<Message>> {
use Message::*;
match message {
Value(v) => {
self.value = v;
}
_ => {
println!("Received message {message:#?}");
}
}
Task::none()
}
fn load(receiver: Receiver<u8>) -> Task<Message> {
let boxed_stream = futures::stream::unfold(receiver.clone(), move |state| {
async move {
match state.recv() {
Ok(number) => {
println!("boxed_stream returning message");
Some((Value(number), state.clone()))
}
Err(e) => {
None
}
}
}
});
Task::run(boxed_stream, |m| m)
}
fn view(&self) -> Element<Message> {
text(format!("Value: {}", self.value)).size(20).into()
}
fn subscription(&self) -> Subscription<Message> {
Subscription::batch(vec![
iced::time::every(Duration::from_millis(100))
.map(|_| Message::Tick)
]
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment