S3ClientFactory { @NonNull synchronized Observable<Optional<AmazonS3Client>> getAmazonS3() { if (amazonS3ReplaySubject == null) { amazonS3ReplaySubject = ReplaySubject.createWithSize(1); if (cognitoManager instanceof CognitoManagerImpl) { amazonS3Disposable = ((CognitoManagerImpl)cognitoManager).getCognitoCachingCredentialsProvider() .<Optional<AmazonS3Client>>map(cognitoCachingCredentialsProvider -> { if (cognitoCachingCredentialsProvider.isPresent()) { return Optional.of(new AmazonS3Client( cognitoCachingCredentialsProvider.get(), Region.getRegion(Regions.US_EAST_1))); } else { return Optional.absent(); } }) .subscribe(amazonS3ClientOptional -> { amazonS3ReplaySubject.onNext(amazonS3ClientOptional); if (amazonS3ClientOptional.isPresent()) { amazonS3ReplaySubject.onComplete(); if (amazonS3Disposable != null) { amazonS3Disposable.dispose(); } } }, throwable -> amazonS3ReplaySubject.onError(throwable), () -> amazonS3ReplaySubject.onComplete()); } } return amazonS3ReplaySubject; } S3ClientFactory(@NonNull CognitoManager cognitoManager);   }
@Test public void getAmazonS3() { s3ClientFactory.getAmazonS3().test() .assertComplete() .assertNoErrors(); final Optional<AmazonS3Client> s3Client = s3ClientFactory.getAmazonS3().blockingFirst(); assertTrue(s3Client.isPresent()); }
@Test public void getAmazonS3WhenInitiallyAbsent() { final BehaviorSubject<Optional<CognitoCachingCredentialsProvider>> subject = BehaviorSubject.create(); when(cognitoManager.getCognitoCachingCredentialsProvider()).thenReturn(subject); subject.onNext(Optional.<CognitoCachingCredentialsProvider>absent()); TestObserver<Optional<AmazonS3Client>> testObserver = s3ClientFactory.getAmazonS3().test(); testObserver .assertValueCount(1) .assertNotComplete() .assertNoErrors(); final Optional<AmazonS3Client> s3Client1 = s3ClientFactory.getAmazonS3().blockingFirst(); assertFalse(s3Client1.isPresent()); subject.onNext(Optional.of(cognitoCachingCredentialsProvider)); testObserver.assertComplete(); testObserver.assertNoErrors(); final Optional<AmazonS3Client> s3Client2 = s3ClientFactory.getAmazonS3().blockingFirst(); assertTrue(s3Client2.isPresent()); }