Created
July 11, 2024 17:27
-
-
Save cbeust/21dd8d3824baba6d4ad333d02e90104c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::time::Duration; | |
use futures::{SinkExt, StreamExt}; | |
use iced::{Element, Length, Subscription, Task}; | |
use iced::widget::{Column, text_input, Text}; | |
/// An example showing how a channel can generate values which can then be | |
/// mapped into Messages that get sent to your application. | |
/// In this example, the sender sends integers and the GUI only displays even values. | |
pub fn channel_to_messages() -> iced::Result { | |
iced::application("test", MyApp::update, MyApp::view) | |
.subscription(MyApp::subscription) | |
.run_with(move || | |
{ | |
MyApp { | |
value: 0, | |
} | |
} | |
) | |
} | |
#[derive(Clone, Debug)] | |
enum Message { | |
OnInput(String), | |
Value(i32), | |
Tick, | |
} | |
struct MyApp { | |
value: i32, | |
} | |
impl MyApp { | |
fn subscription(&self) -> Subscription<Message> { | |
let s = iced::subscription::channel(0, 100, |mut output| async move { | |
let (mut sender, mut receiver) = futures::channel::mpsc::channel(100); | |
/// Spawn the sender, which sends integers every second | |
tokio::spawn(async move { | |
let mut i = 0; | |
loop { | |
sender.send(i).await.unwrap(); | |
i += 1; | |
::tokio::time::sleep(Duration::from_secs(1)).await; | |
} | |
}); | |
/// Only send even numbers to the application | |
loop { | |
::tokio::time::sleep(Duration::from_secs(2)).await; | |
let n = receiver.select_next_some().await; | |
if (n % 2) == 0 { | |
output.send(Message::Value(n)).await.unwrap(); | |
} | |
} | |
}); | |
Subscription::batch([s]) | |
} | |
fn update(&mut self, message: Message) -> Task<Message> { | |
match message { | |
Message::Value(value) => self.value = value, | |
_ => {} | |
} | |
Task::none() | |
} | |
fn view(&self) -> Element<'_, Message> { | |
Column::new() | |
.push(Text::new(self.value)) | |
.push(text_input("", "Text").width(Length::Fixed(100.0)).on_input(Message::OnInput)) | |
.into() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment