Using st.cache_resource for a generator

What is the appropriate way to use st. cache_resource for a generator object?

This generator feeds a realtime data stream, depending on certain conditions it creates a button.

However when clicking on the button the whole application is reloaded which causes all the variables to be nulled apart from the cache of the streamlit application.

This is a complex generator which is not pickleable therefore storing it as a session_state is not viable. I have attempted to use the stream st.cache_resource but since it is a async generator object error I get the following error.

Exception has occurred: StopException       (note: full exception trace is shown but execution is paused at: <module>)
exception: no description
  File "consumer/Latest_block.py", line 106, in main
    async for tx in data_stream():
                    ^^^^^^^^^^^^^
  File "consumer/Latest_block.py", line 121, in <module> (Current frame)
    asyncio.run(main())
streamlit.runtime.scriptrunner_utils.exceptions.StopException:

Any recommendations for working around such issue?

There are many ways, what the proper one is depends on your needs. This works for me.

import streamlit as st

@st.cache_resource
def generator():
    i = 0
    while True:
        yield i
        i = i + 1

st.write(next(generator()))
st.button("Rerun")