我在后端(tauri)上有一个命令返回一个字符串(从windows注册表的轻主题值).我需要把它放在前端+听如果这个字符串改变.我在leptos或tauri docs中找不到所需的函数. 所以我想出了这个拐杖在前端:

let (is_light_theme, set_is_light_theme) = create_signal(String::new());

let is_light_theme_fn = move || {
        spawn_local(async move {
            let is_light_theme_fetch = invoke("is_light_theme", to_value("").unwrap())
                .await
                .as_string()
                .unwrap();
            set_is_light_theme.set(_is_light_theme_);
            loop {
                let old_value = is_light_theme.get();
                let new_value = invoke("is_light_theme", to_value("").unwrap())
                    .await
                    .as_string()
                    .unwrap();
                if new_value != old_value {
                    set_is_light_theme.set(new_value);
                };
                // sleep(Duration::from_millis(2000)).await; // breaks loop
            }
        });
    };
    is_light_theme_fn();

在后端执行tauri命令:

#[tauri::command]
fn is_light_theme() -> String {
    let theme = helpers::is_light_theme();
    format!("{}", theme)
}

is_light_theme名助手:

pub fn is_light_theme() -> bool {
    let val = CURRENT_USER
        .open(r#"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"#)
        .expect("Failed to get registry key")
        .get_u32("AppsUseLightTheme")
        .expect("Failed to get registry value");
    println!("{}", val);
    val != 0
}

这运行得有点不错,但这个循环非常需要处理. 我试着把sleep从std:thread和tokio添加到循环中,它们都 destruct 了它.

也许有一种更好的方法来监听后端的价值变化?

推荐答案

后端-&>前端

您可以使用Tauri events:

// in your setup routine or tauri command function, where you can have access to the app handle
app.emit_all("event-name", Payload { message: "Tauri is awesome!".into() }).unwrap();

然后听前面的这个事件:

import { emit, listen } from '@tauri-apps/api/event'

const unlisten = await listen('event-name', (event) => {
  // event.payload is the payload object
  console.log(event);
})

==

前端-&>后端

持续轮询数据通常是一个坏主意,我可能不完全理解你的用例,但如果我需要从前端获取主题,我会怎么做.

我会使用状态管理来代替:

use std::sync::Mutex;
use tauri::State;

struct Theme {
    theme: Mutex<String>,
}

fn main() {
    tauri::Builder::default()
                .manage(Theme { theme: Mutex::new(String::from("default")) })
        .invoke_handler(tauri::generate_handler![update_theme])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

#[tauri::command]
fn update_theme(new_theme: String, state: State<Theme>) {
        let mut theme = state.theme.lock().unwrap();
        *theme = new_theme;
}

Rust相关问答推荐

从特征实现调用函数的Rust惯用方法

MacOS(AARCH64)上Ghidra中的二进制补丁导致进程终止

如何使用syn插入 comments ?

Box::new()会从一个堆栈复制到另一个堆吗?

在决定使用std::Sync::Mutex还是使用Tokio::Sync::Mutex时,操作系统线程调度是考虑因素吗?

如何导入crate-type=[";cdylib;]库?

如何模拟/创建ReqData以测试Actix Web请求处理程序?

一种随机局部搜索算法的基准(分数)

为什么 tokio 在以奇怪的方式调用时只运行 n 个任务中的 n-1 个?

Rust 重写函数参数

Rust 文件未编译到 dll 中

为什么我们有两种方法来包含 serde_derive?

为什么这个闭包没有实现Fn?

Rust编译器通过哪些规则来确保锁被释放?

有没有更好的方法来为拥有 DIsplay 事物集合的 struct 实现 Display?

有没有办法隐藏类型定义?

如何将 u8 切片复制到 u32 切片中?

Rust 中的运行时插件

如何在 Rust 的内置函数上实现特征?

为什么在使用 self 时会消耗 struct 而在解构时不会?