I’m trying to use the fragment feature to run different sections of an app independently
of each other. My attempt is shown below which contains two fragments: a button that calls a slow function where the result updates some text and a slider that updates some text with the slider value.
import streamlit as st
import time
def slow_adder(x: float, y: float) -> float:
"""Slow function for adding two numbers."""
time.sleep(5)
z = x + y
return z
@st.fragment
def add_numbers():
"""Button to add numbers."""
if st.button("Add numbers"):
with st.spinner():
result = slow_adder(2, 8.4)
st.markdown(f"Result of 2 + 8.4 is {result}")
@st.fragment
def age_slider():
"""Slider to change value."""
st.markdown("Try this slider while button runs")
age = st.slider("Select age")
st.markdown(f"My age is {age}")
def main():
"""Run the app."""
st.subheader("Button Fragment")
add_numbers()
st.divider()
st.subheader("Slider Fragment")
age_slider()
if __name__ == "__main__":
main()
Here is an image of what the app looks like:
If I click the button and use the slider at the same time, the slider waits until the button fragment is done before it updates the "My age is " text with the slider value. I would expect the button and slider content to act independently of each other since they are both in a fragment. But it seems like the content in the slider fragment must wait until the button fragment is done running. Is there something I’m doing wrong here? How do I get the button and slider sections of the app to run independently?