How to call another function while waiting after asynchronous function calls?

fn stram_klines(&self, _symbol: &str, _interval: &str) {
        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        rt.block_on(async {
            let keep_running = AtomicBool::new(true); 
            let kline = kline_stream("btcusdt", "1m");
            let mut websocket: WebSockets<'_, WebsocketEvent> = WebSockets::new(|event: WebsocketEvent| {
                match event {
                    WebsocketEvent::Kline(kline_event) => {
                        debug!( "Symbol: {}, high: {}, low: {}",
                        kline_event.kline.symbol, kline_event.kline.low, kline_event.kline.high );
                    }
                    _ => (),
                }
                Ok(())
            });

            websocket.connect(&kline).await.unwrap();
            if let Err(e) = websocket.event_loop(&keep_running).await {
                println!("Error: {e}");
                println!("waiting");
                tokio::time::sleep(Duration::from_secs(20)).await;
            };

            websocket.disconnect().await.unwrap();
            println!("disconnected");
        });
    }

I want to call websocket.connect after websocket.connect, but websocket.connect is not finished, so I can't call websocket.disconnect.

Please help if anyone knows how to terminate the websocket connection.

I'm always grateful to those who help.

You can await results of multiple futures with futures::join! or futures::join_all.

You can use spawn to make a future polled independently on its own, without having to await.

BTW, you usually shouldn't create an instance of a runtime inside a function. If it needs to await, make it async fn itself, and make starting the runtime the caller's problem, all the way up to main().

If you have to make a synchronous function, then instead of starting a runtime, make it use a Handle to an existing runtime, so that your program can use a single shared runtime, configured in one place.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.