Skip to content

Commit

Permalink
Rust から JS へのイベント通知を実装 in tauri/tauri-app-event.
Browse files Browse the repository at this point in the history
  • Loading branch information
mikoto2000 committed Mar 23, 2022
1 parent 1030a77 commit 763da70
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 2 deletions.
33 changes: 32 additions & 1 deletion tauri/tauri-app-event/dist/index.html
Expand Up @@ -10,11 +10,42 @@
}

body {
display: flex;
align-items: center;
justify-content: center;
}
</style>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
const invoke = window.__TAURI__.invoke;
const listen = window.__TAURI__.event.listen;
const emit = window.__TAURI__.event.emit;

async function init() {
// バックエンドの初期化処理呼び出し
await invoke('post_setup_process_for_backend', {});

// バックエンドが emit するイベントの listen
const unlistenBackendHello = await listen('backendHello', event => {
console.log(event);
const p = document.createElement('p');
p.textContent = event.payload.message;
document.body.append(p);
});

// 5 秒後に listen を止める
setTimeout(() => {
console.log("timeout.");
unlistenBackendHello();
const p = document.createElement('p');
p.textContent = 'stop event listen.';
document.body.append(p);
}, 5000);
}

init();

});
</script>
<body>
<h1>tauri-app-event</h1>
</body>
Expand Down
42 changes: 42 additions & 0 deletions tauri/tauri-app-event/src-tauri/src/command.rs
@@ -0,0 +1,42 @@
use std::sync::mpsc::{self, TryRecvError};
use std::thread;
use std::time::Duration;

use tauri;
use tauri::Manager;

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct BackendHelloEventPayload {
pub message: String,
}

#[tauri::command]
pub fn post_setup_process_for_backend(app: tauri::AppHandle) {

let (tx, rx) = mpsc::channel();

// 新しいスレッドを作成して、 1 秒ごとにイベントを emit する処理を実装
tauri::async_runtime::spawn( async move {
loop {
println!("send backendHello event.");
thread::sleep(Duration::from_millis(1000));
app.emit_all("backendHello", BackendHelloEventPayload { message: "Hello, World from backend!!!".into() }).unwrap();

// emit 終了通知用チャンネルに通知が来たらループをストップ
match rx.try_recv() {
Ok(_) | Err(TryRecvError::Disconnected) => {
println!("stop backendHello event.");
break;
}
Err(TryRecvError::Empty) => {}
}
}
});

// 10 秒後に emit を終了(emit 終了通知用チャンネル経由でストップを通知)
tauri::async_runtime::spawn( async move {
thread::sleep(Duration::from_millis(10000));
let _ = tx.send(());
});
}

5 changes: 5 additions & 0 deletions tauri/tauri-app-event/src-tauri/src/main.rs
Expand Up @@ -3,8 +3,13 @@
windows_subsystem = "windows"
)]

mod command;

fn main() {
tauri::Builder::default()
// setup 中ではできない初期化処理を実行するコマンドを登録
// setup 中に spawn ができないので、それを行う
.invoke_handler(tauri::generate_handler![command::post_setup_process_for_backend])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
3 changes: 2 additions & 1 deletion tauri/tauri-app-event/src-tauri/tauri.conf.json
Expand Up @@ -7,7 +7,8 @@
"distDir": "../dist",
"devPath": "../dist",
"beforeDevCommand": "",
"beforeBuildCommand": ""
"beforeBuildCommand": "",
"withGlobalTauri": true
},
"tauri": {
"bundle": {
Expand Down

0 comments on commit 763da70

Please sign in to comment.