Hi there! In many articles about collecting Flow i...
# android
n
Hi there! In many articles about collecting Flow in an Android lifecycle aware manner there is
SharingStarted.WhileSubscribed(5000L)
in
stateIn
operator. Where does the 5000 come from? Why not zero and why exactly that number? Thanks in advance.
a
It's partially arbitrary but partially related to the ANR timeout for Android apps becoming unresponsive on the main thread. When an activity is recreated the old activity will be torn down before the new one's lifecycle gets to started or resumed. If you use no timeout then this can result in the number of subscribers dropping to zero and repeating potentially expensive work to restart the upstream flow from scratch. If your app takes longer than 5 seconds to create your new activity instance and move forward through its lifecycle callbacks then you're already likely to get an ANR timeout and the user will be prompted to kill your app.
🍻 2
LiveData historically used the same timeout for the same reasons and the prescription carried over to StateFlows that get shared across activity recreation
🙌 1
n
👍 thank you, that makes sense
👍 1