untracking activities during espresso runs as soon as they're idle

- Sometimes activities are instantly idle without going through the lifecycleChanged callback which means we were registering callsbacks which were duplicated and triggering for later waits
This commit is contained in:
Adam Brown 2022-01-26 17:46:23 +00:00
parent d127e0c39d
commit 19a46afe7b

View file

@ -160,43 +160,50 @@ fun initialSyncIdlingResource(session: Session): IdlingResource {
}
fun activityIdlingResource(activityClass: Class<*>): IdlingResource {
val lifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance()
val res = object : IdlingResource, ActivityLifecycleCallback {
private var callback: IdlingResource.ResourceCallback? = null
private var resumedActivity: Activity? = null
private val uniqTS = System.currentTimeMillis()
var hasResumed = false
private var currentActivity: Activity? = null
val uniqTS = System.currentTimeMillis()
override fun getName() = "activityIdlingResource_${activityClass.name}_$uniqTS"
override fun isIdleNow(): Boolean {
val currentActivity = currentActivity ?: ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED).elementAtOrNull(0)
val activity = resumedActivity ?: ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED).firstOrNull {
activityClass == it.javaClass
}
val isIdle = hasResumed || currentActivity?.javaClass?.let { activityClass.isAssignableFrom(it) } ?: false
println("*** [$name] isIdleNow activityIdlingResource $currentActivity isIdle:$isIdle")
val isIdle = activity != null
if (isIdle) {
unregister()
}
return isIdle
}
override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback?) {
println("*** [$name] registerIdleTransitionCallback $callback")
this.callback = callback
// if (hasResumed) callback?.onTransitionToIdle()
}
override fun onActivityLifecycleChanged(activity: Activity?, stage: Stage?) {
println("*** [$name] onActivityLifecycleChanged $activity $stage")
currentActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED).elementAtOrNull(0)
val isIdle = currentActivity?.javaClass?.let { activityClass.isAssignableFrom(it) } ?: false
println("*** [$name] onActivityLifecycleChanged $currentActivity isIdle:$isIdle")
if (isIdle) {
hasResumed = true
println("*** [$name] onActivityLifecycleChanged callback: $callback")
callback?.onTransitionToIdle()
ActivityLifecycleMonitorRegistry.getInstance().removeLifecycleCallback(this)
if (activityClass == activity?.javaClass) {
when (stage) {
Stage.RESUMED -> {
unregister()
resumedActivity = activity
println("*** [$name] onActivityLifecycleChanged callback: $callback")
callback?.onTransitionToIdle()
}
}
}
}
private fun unregister() {
lifecycleMonitor.removeLifecycleCallback(this)
}
}
ActivityLifecycleMonitorRegistry.getInstance().addLifecycleCallback(res)
lifecycleMonitor.addLifecycleCallback(res)
return res
}