Hello, is it safe to use `repeatOnLifecycle` in a...
# android
s
Hello, is it safe to use
repeatOnLifecycle
in an activity like so?
Copy code
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AppUi()
        }

        lifecycleScope.launch {
            repeatOnLifecycle(state = Lifecycle.State.CREATED) {
                userIdFlow.collect { userId ->
                    log.d("userId: $userId")
                    updateAppCenterUserId(userId)
                }
            }
        }
    }
}
Looking at some logs from production environment I've seen cases where the
userId
is logged several times in a row, looking as if
userIdFlow.collect
was called multiple times. Right before aforementioned logs it seems like there is around ~15 minutes of inactivity in the app.
userIdFlow
is initiated by
MutableStateFlow<String?>(null)
There might be an issue that several file logging Timber trees were planted, but other log calls don't seem to be repeated this way.
a
Can you also log how much times
repeatOnLifecycle(state = Lifecycle.State.CREATED) {
and
userIdFlow.collect { userId ->
getting called. code snippet seems correct. It should only register when lifecycle moved to
CREATED
state and should deregister when lifecycle moves to
DESTROYED
sate
a
@Stanislav Kral try to collect from flow when the lifecycle is at least
STARTED
and cancel when the lifecycle is
STOPPED
.