Using session_state within socketio client events

The error you encountered suggests that the event listener function (catch_all) executed by the socketio library is running in a separate thread, which doesnโ€™t have access to the st.session_state object. This is because st.session_state is specific to the Streamlit framework and is not designed to be shared across different threads or external libraries.

To work around this limitation and achieve communication between your Streamlit app and the socketio server, you can consider the following approach:

  1. Instead of directly modifying st.session_state, create a separate object or data structure to store the shared state between the socketio events and your Streamlit app.

  2. In your Streamlit app, define a Streamlit SessionState class (or use an existing implementation) that can handle shared state across different sessions. Hereโ€™s an example implementation:

class SessionState:
    def __init__(self):
        self.some_boolean = True
        self.some_param = 50

session_state = SessionState()
  1. Modify your event listener function (catch_all) to update the shared state object (session_state) instead of modifying st.session_state. For example:
def catch_all(messageType, value):
    if session_state.some_boolean:
       session_state.some_param = value
  1. In your Streamlit app, use the session_state object to access and display the shared state values. For example:
st.write("Some Boolean:", session_state.some_boolean)
st.write("Some Parameter:", session_state.some_param)

By following this approach, you create a separate shared state object that can be accessed and modified by both the event listener function and your Streamlit app. This way, you can achieve communication between the socketio server and your Streamlit app while avoiding conflicts with st.session_state.

Remember to manage synchronization and potential race conditions if multiple threads are modifying the shared state simultaneously. Using appropriate synchronization primitives like locks or thread-safe data structures can help ensure data consistency and avoid conflicts.

Note: The provided example is a basic implementation to demonstrate the concept of shared state. Depending on your specific requirements, you may need to adapt and enhance it to suit your needs.

1 Like