#tauri emit update all at once at the end of for loop

2 messages · Page 1 of 1 (latest)

coarse cove
#

hi

#[tauri::command]
pub fn start<'a>(number_of_try: i32, effects: Vec<Effect>, state: State<'a, Mutex<OcrState>>) -> Result<(), String> {


    let mut global_item = GLOBAL_ITEM.lock().map_err(|_| "Failed to lock GLOBAL_ITEM in start_fm")?;


    for effect in &effects {
        if let Some(global_effect) = global_item.effects.iter_mut().find(|e| e.index_on_item == effect.index_on_item) {
            global_effect.desired_value = effect.desired_value;
        }
    }

    for _ in 0..number_of_try {
        if let Some(action) = global_item.next_best_action() {
            update_effect_value(&state, &mut global_item);
        }
    }

    Ok(())
}


fn update_effect_value<'a>(state: &State<'a, Mutex<OcrState>>, global_item: &mut Item) -> Result<(), String> {
    let global_handle = GLOBAL_APP_HANDLE.lock().map_err(|_| "Failed to lock GLOBAL_APP_HANDLE")?;
    if let Some(app_handle) = &*global_handle {
        println!("Emitting update-item event...");

        app_handle.emit_all("update-item", Payload { message: serialized_effects })
            .map_err(|_| "Failed to emit update-item event")?;
    }

    Ok(())
}



    async function startSerialEventListener() {
        console.log("Starting serial event listener...");
        await listen<Payload>('update-item', (event) => {
            try {
                const parsedMessage = JSON.parse(event.payload.message) as ItemEffect[];
                console.log("Event payload:", parsedMessage);
                setInit(parsedMessage);
            } catch (error) {
                console.error("Failed to parse event payload:", error);
            }
        });
    }

    useEffect(() => {
        startSerialEventListener();
    }, []);

i got a problem it work but it send all the emit at once at the end of the for loop, so this is not dynamic and i can't see the progress in live

delicate salmon
#

I think you are blocking the tauri runtime by locking a global app handle from a "sync" command, not really knowing why you have a global app handle and so much locking without cloning I am not sure I fully understand it though.

Is there some restriction I don't know about? Tauri commands have the app handle injected so the function can just use app: AppHandle and it will work (https://v2.tauri.app/develop/calling-rust/#accessing-an-apphandle-in-commands) and you can pass this handle to the update effect function.

Next would be that your start command will be "sync" so if your intention is some longer running async emit called from the command then you should make it async to prevent it blocking the main UI thread.