I am trying to build a chat among users of the same app, and in order to send and receive messages, I probably need to use a websocket. However, I’m encountering threading issues, which I’m not sure to fully understand:
- When using
st.fragment
to hopefully rerun just the part of receiving messages, if the function currently rerun byst.fragment
is taking a while to process (which is normal when receiving messages), no other rerun can be triggered, the whole app gets stuck. - Without
st.fragment
, a long running task will continue to run in the background until it meets a streamlit statement (I am however able to modify objects inst.session_state
, as long as I referenced them before and don’t callst.session_state
directly).
I came to understand that multithreading in streamlit doesn’t work super well due to how streamlit is build to ensure reruns, but I would have expected similar behaviours with and without st.fragment
.
You can reproduce the behaviours I described using the following code snippet:
import time
import streamlit as st
@st.fragment()
def instant_section():
print(“In instant section”)
st.button(“Rerun instant section”)
@st.fragment
def long_section():
print(“In long section”)
if st.button(“Start long process”):
for i in range(100):
time.sleep(1)
print(f"Loop {i}")
st.empty()
instant_section()
long_section()
- If you run this and trigger the long process, you won’t be able to trigger a rerun of the instant section with the corresponding button.
- If you comment the two
st.fragment
lines and trigger the long process, when you click on the instant button, the long process will print one more time and then exit due to thest.empty()
. - If you also comment the
st.empty()
, then the long process will continue running in the background until it’s done, even if you trigger a rerun with the instant button. You can even start another long process that will run in parallel.
Is this expected behaviour with st.fragment
? Any advice on running parallel tasks while still being able to rerun the rest of the app?
Streamlit version: 1.40.1
Python version: 3.10.14