How to run a slow task on button:click? #1848
-
I'm trying to PGP encrypt a string client side when user clicks on a button and this seems to be super slow.
use base64::{engine::general_purpose, Engine as _};
use leptos::*;
use sequoia_openpgp::serialize::stream::{Encryptor, LiteralWriter, Message};
use std::io::Write;
#[component]
pub fn App() -> impl IntoView {
let (data, set_data) = create_signal("".to_string());
view! {
<div>
<pre>{move || data.get()}</pre>
<button on:click=move |_| {
let mut sink = vec![];
let message = Encryptor::with_passwords(Message::new(&mut sink), Some("password"))
.build()
.unwrap();
let mut w = LiteralWriter::new(message).build().unwrap();
let _ = w.write_all(b"Hello world.");
let _ = w.finalize();
let b64 = general_purpose::STANDARD.encode(sink);
set_data.set(b64.clone());
}
>
"Encrypt"
</button>
</div>
}
}
pub fn main() {
mount_to_body(|| {
view! {
<App />
}
})
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 8 replies
-
I'm having trouble getting I don't think the question really has anything to do with Leptos — it's blocking on the processing time inside your callback, right? I'm totally unfamiliar with the domain here unfortunately. What's your equivalent JS code? If it's using some browser built-ins you might as well use those instead of compiling in additional Rust dependencies. |
Beta Was this translation helpful? Give feedback.
Oh, sure! Using async for an intentionally-slow task makes a ton of sense: an async approach here would basically do some work, set a timer or something, yield back to the browser until the timer goes off, then come back and do some more work, etc. Basically if what's causing the slowness is computation, async can't help you (although it can spread it out into non-blocking chunks). But if what's causing the slowness is intentionally blocking the thread for a period of time, async is ideal.
To an async task from the click handler just use
spawn_local
.