jabber-tools / cognitive-services-speech-sdk-rs

Apache License 2.0
24 stars 15 forks source link

Using async inside callbacks #10

Closed jBernavaPrah closed 6 months ago

jBernavaPrah commented 6 months ago

Hi,

First of all, thanks for this package!

I'm still learning rust, so sorry if they are silly questions.

  1. How to execute async calls inside callbacks?

Currently, I achieve it using a new Tokio runtime:

speech_recognizer
            .set_recognized_cb(move |event| {
                println!("Event!");
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .unwrap();
                let tx = tx.clone();

                rt.block_on(async move {
                    println!("here 3 {:?}", event);
                    if (tx.send(event.result.text).await.is_err()) {
                        println!("tx not working!")
                    }
                });
            })
            .unwrap();

There is a better way to do it?

  1. How may I continue to listen to the microphone indefinitely?

Could a loop with sleep do it?

loop {
    tokio::sleep(Duration::from_millis(100)).await;
}

Thanks for your time!

adambezecny commented 6 months ago

hi,

it is quite a long time I did not touch this library :)

ad 1) I don't think you can really put async function into callback, because this function is actually passed into underlying C code. Callbacks should ideally execute quickly in non blocking way. If you still need to execute async code try using tokio::spawn or tokio::task::spawn_blocking. Spinning up whole tokio in callback as you do is highly ineffective. You can also try using sync channels and in callback simply forward/send message into channel. Receiver can then process tasks again by tokio:spawn or similar technique.

ad 2) example must use sleep to prevent main thread from terminating. this is just simple example. In reality you would have som long running process like web server that will be processing this in separate tokio tasks.

To get deeper understanding of rust async programming I suggest going thoroughly through following tokio tutorial: https://tokio.rs/tokio/tutorial

good luck with Rust endevours :)