Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Examples: async request no blocking main thread #1578

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ glow = { version = "0.13.0", optional = true }
epoxy = { version = "0.1.0", optional = true }
libloading = { version = "0.8.0", optional = true }
im-rc = { version = "15", optional = true }
async-channel = { version = "2.1.1", optional = true }
tokio = { version = "1", features = ["full"], optional = true }
reqwest = { version = "0.11", features = ["json", "rustls-tls"], default-features = false, optional = true }
serde = { version = "1.0", features = ["derive"], optional = true }

gtk.workspace = true

# used by gif-paintable example
Expand All @@ -26,6 +31,7 @@ optional = true
default = []
femtovg-support = ["epoxy", "femtovg", "glow", "libloading"]
glium-support = ["glium", "epoxy", "libloading"]
tokio = ["dep:tokio", "async-channel", "reqwest", "serde"]
v4_10 = ["gtk/v4_10"]
v4_12 = ["gtk/v4_12"]
v4_14 = ["gtk/v4_14"]
Expand Down Expand Up @@ -192,6 +198,11 @@ name = "text_viewer"
path = "text_viewer/main.rs"
required-features = ["v4_10"]

[[bin]]
name = "tokio_async_request"
path = "tokio_async_request/main.rs"
required-features = ["tokio"]

[[bin]]
name = "video_player"
path = "video_player/main.rs"
Expand Down
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,6 @@ cargo run --bin basics
- [Squares](./squares/)
- [Squeezer Bin](./squeezer_bin/)
- [TextView](./text_viewer/)
- [Tokio Async Request](./tokio_async_request/)
- [Video Player](./video_player/)
- [Virtual Methods](./virtual_methods/)
5 changes: 5 additions & 0 deletions examples/tokio_async_request/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Tokio async request

This example shows an infinite list of pokemon names, whenever it reaches the end, it searches for new names and fills the list without blocking the main thread of the program.

![Screenshot](screenshot.gif)
110 changes: 110 additions & 0 deletions examples/tokio_async_request/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
use glib::clone;
use gtk::prelude::*;
use gtk::{glib, Application, ApplicationWindow};
use serde::Deserialize;
use std::sync::OnceLock;
use tokio::runtime::Runtime;

#[derive(Deserialize, Debug)]
pub struct Pokemon {
pub name: String,
}

#[derive(Deserialize, Debug)]
pub struct ResultBody {
results: Vec<Pokemon>,
}

#[derive(Debug)]
pub struct PokemonClient {
page: u32,
}

impl Default for PokemonClient {
fn default() -> Self {
Self { page: 0 }
}
}

impl PokemonClient {
const URI: &'static str = "https://pokeapi.co/api/v2/pokemon";
const PAGE_LIMIT: &'static str = "100";

pub async fn get_pokemon_list(&mut self) -> Result<Vec<Pokemon>, reqwest::Error> {
let current_offset = self.page.to_string();
let params: [(&str, &str); 2] = [
("limit", Self::PAGE_LIMIT),
("offset", current_offset.as_str()),
];
let url = reqwest::Url::parse_with_params(Self::URI, params).unwrap();
let body = reqwest::get(url).await?.json::<ResultBody>().await?;

self.page += 10;
Ok(body.results)
}
}

fn runtime() -> &'static Runtime {
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
RUNTIME.get_or_init(|| Runtime::new().expect("Setting up tokio runtime needs to succeed."))
}

fn main() -> glib::ExitCode {
let app = Application::builder()
.application_id("org.gtk_rs.pokemon.list")
.build();
app.connect_activate(build_ui);
app.run()
}

fn build_ui(app: &Application) {
let (sender, receiver) = async_channel::bounded::<Result<Vec<Pokemon>, reqwest::Error>>(1);
runtime().spawn(clone!(@strong sender => async move {
let mut pokemon_client = PokemonClient::default();
let pokemon_vec = pokemon_client.get_pokemon_list().await;
sender.send(pokemon_vec).await.expect("The channel needs to be open.");
}));

let list_box = gtk::ListBox::builder().build();
let scrolled_window = gtk::ScrolledWindow::builder()
.hscrollbar_policy(gtk::PolicyType::Never)
.min_content_width(360)
.child(&list_box)
.build();

scrolled_window.connect_edge_reached(move |_, position| {
let mut pokemon_client = PokemonClient::default();
if gtk::PositionType::Bottom == position {
runtime().spawn(clone!(@strong sender => async move {
let pokemon_vec = pokemon_client.get_pokemon_list().await;
sender.send(pokemon_vec).await.expect("The channel needs to be open.");
}));
}
});

glib::spawn_future_local(async move {
while let Ok(response) = receiver.recv().await {
match response {
Ok(response) => {
for pokemon in response {
let label = gtk::Label::new(Some(&pokemon.name));
label.set_halign(gtk::Align::Start);
list_box.append(&label);
}
}
Err(_) => {
println!("bad request");
}
}
}
});

let window = ApplicationWindow::builder()
.application(app)
.title("Tokio integration")
.default_width(600)
.default_height(300)
.child(&scrolled_window)
.build();
window.present();
}
Binary file added examples/tokio_async_request/screenshot.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading