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 12 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
15 changes: 15 additions & 0 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@ 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 }

[dependencies.gtk]
path = "../gtk4"
package = "gtk4"
features = ["v4_10"]
Claudio-code marked this conversation as resolved.
Show resolved Hide resolved
gtk.workspace = true

# used by gif-paintable example
Expand All @@ -26,6 +35,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 +202,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)
107 changes: 107 additions & 0 deletions examples/tokio_async_request/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
use glib::clone;
use gtk::glib::once_cell::sync::Lazy;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are removing once_cell usage from our crates, so you should use std::sync::OnceLock here instead

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't do this and it ends up giving errors because of the listbox, but if you instantiate it within the lambda there is no way for the ScrolledWindow to receive its value. Can you show me an example of what this implementation would look like?

error:
Screenshot from 2024-01-28 15-23-46

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I achieved resolve

use gtk::prelude::*;
use gtk::{glib, Application, ApplicationWindow};
use serde::Deserialize;
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 PokemonClient {
const URI: &'static str = "https://pokeapi.co/api/v2/pokemon";
const PAGE_LIMIT: &'static str = "100";

pub fn new() -> Self {
Self { page: 0 }
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could derive Default and use that instead


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)
}
}

static RUNTIME: Lazy<Runtime> =
Lazy::new(|| 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::new();
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::new();
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