title: Loading image synchronously with Glide
body: <p>I want to write an Espresso matcher that verifies that an `ImageView´ has a specific bitmap set. Since the app does its loading of images via Glide, I thought I have to do the same on the test side to account for cropping / centering before I can actually compare the expected and actual bitmaps.</p>
  
  <p>Here is what I came up with so far:</p>
  
  <pre><code>BitmapRequestBuilder&lt;Uri, Bitmap&gt; bitmapRequest = Glide.with(imageView.getContext())
          .load(Uri.parse("file:///android_asset/" + mPath))
          .asBitmap();
  
  switch (imageView.getScaleType()) {
      case CENTER_CROP:
          bitmapRequest.centerCrop();
          break;
      case FIT_CENTER:
      case FIT_START:
      case FIT_END:
          bitmapRequest.fitCenter();
          break;
      default:
          // no scaling applied to the ImageView under test
  }
  
  AtomicReference&lt;Bitmap&gt; bmRef = new AtomicReference&lt;&gt;();
  bitmapRequest.into(new SimpleTarget&lt;Bitmap&gt;(
              imageView.getMeasuredWidth(), 
              imageView.getMeasuredHeight()
  ) {
      @Override
      public void onResourceReady(Bitmap resource, GlideAnimation&lt;? super Bitmap&gt; glideAnimation) {
          bmRef.set(resource);
      }
  });
  
  // ???
  
  try {
      Bitmap expected = bmRef.get();
      return expected.sameAs(bitmap);
  } catch (Exception e) {
      throw new IllegalStateException("could not load asset " + mPath, e);
  }
  </code></pre>
  
  <p>Now the issue here is of course that I have a deadlock. I'm on the main thread (the matcher is executed on the main thread IIRC) and Glide wants a backend thread to load the bitmap and then returns on the main thread (in 'onResourceReady') itself. So I need to wait from the outside for the result that is posted on the inside, while keeping the main thread running.</p>
  
  <p>I (unsuccessfully) tried to advance the current looper via <code>Looper.loop()</code> in <code>// ???</code> and also tried the regular lock / wait approach, but nothing worked. I'm out of ideas...</p>