15
15
package com .google .firebase .perf .application ;
16
16
17
17
import static com .google .common .truth .Truth .assertThat ;
18
+ import static com .google .firebase .perf .application .AppStateMonitor .AppStateCallback ;
18
19
import static com .google .firebase .perf .v1 .ApplicationProcessState .FOREGROUND_BACKGROUND ;
19
20
import static org .mockito .ArgumentMatchers .any ;
20
21
import static org .mockito .ArgumentMatchers .nullable ;
@@ -670,9 +671,11 @@ public void activityStateChanges_singleSubscriber_callbackIsCalled() {
670
671
AppStateMonitor monitor = new AppStateMonitor (transportManager , clock );
671
672
Map <Integer , ApplicationProcessState > subscriberState = new HashMap <>();
672
673
674
+ // Register callbacks, but note that each callback is saved in a local variable. Otherwise
675
+ // WeakReference can get garbage collected, making this test flaky.
673
676
final int subscriber1 = 1 ;
674
- monitor . registerForAppState (
675
- new WeakReference <>(newState -> subscriberState . put ( subscriber1 , newState ) ));
677
+ AppStateCallback callback1 = newState -> subscriberState . put ( subscriber1 , newState );
678
+ monitor . registerForAppState ( new WeakReference <>(callback1 ));
676
679
677
680
// Activity comes to Foreground
678
681
monitor .onActivityResumed (activity1 );
@@ -688,17 +691,19 @@ public void activityStateChanges_multipleSubscribers_callbackCalledOnEachSubscri
688
691
AppStateMonitor monitor = new AppStateMonitor (transportManager , clock );
689
692
Map <Integer , ApplicationProcessState > subscriberState = new HashMap <>();
690
693
694
+ // Register callbacks, but note that each callback is saved in a local variable. Otherwise
695
+ // WeakReference can get garbage collected, making this test flaky.
691
696
final int subscriber1 = 1 ;
692
- monitor . registerForAppState (
693
- new WeakReference <>(newState -> subscriberState . put ( subscriber1 , newState ) ));
697
+ AppStateCallback callback1 = newState -> subscriberState . put ( subscriber1 , newState );
698
+ monitor . registerForAppState ( new WeakReference <>(callback1 ));
694
699
695
700
final int subscriber2 = 2 ;
696
- monitor . registerForAppState (
697
- new WeakReference <>(newState -> subscriberState . put ( subscriber2 , newState ) ));
701
+ AppStateCallback callback2 = newState -> subscriberState . put ( subscriber2 , newState );
702
+ monitor . registerForAppState ( new WeakReference <>(callback2 ));
698
703
699
704
final int subscriber3 = 3 ;
700
- monitor . registerForAppState (
701
- new WeakReference <>(newState -> subscriberState . put ( subscriber3 , newState ) ));
705
+ AppStateCallback callback3 = newState -> subscriberState . put ( subscriber3 , newState );
706
+ monitor . registerForAppState ( new WeakReference <>(callback3 ));
702
707
703
708
// Activity comes to Foreground
704
709
monitor .onActivityResumed (activity1 );
0 commit comments