Skip to content

Instantly share code, notes, and snippets.

@Maragues
Last active August 10, 2016 09:55
Show Gist options
  • Save Maragues/0c0db81a137c8d067396 to your computer and use it in GitHub Desktop.
Save Maragues/0c0db81a137c8d067396 to your computer and use it in GitHub Desktop.
Implementation and usage of an IdlingResource that waits for Picasso actions to finish.

Note that the file lives in the package as Picasso. Otherwise we don't have access to targetToAction

package com.squareup.picasso;

public class PicassoIdlingResource implements IdlingResource, ActivityLifecycleCallback {
  protected ResourceCallback callback;

  WeakReference<Picasso> picassoWeakReference;

  @Override
  public String getName() {
    return "PicassoIdlingResource";
  }

  @Override
  public boolean isIdleNow() {
    if (isIdle()) {
      notifyDone();
      return true;
    } else {
      return false;
    }
  }

  public boolean isIdle() {
    return picassoWeakReference == null
            || picassoWeakReference.get() == null
            || picassoWeakReference.get().targetToAction.isEmpty();
  }

  @Override
  public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
    this.callback = resourceCallback;
  }

  void notifyDone() {
    if (callback != null) {
      callback.onTransitionToIdle();
    }
  }

  @Override
  public void onActivityLifecycleChanged(Activity activity, Stage stage) {
    switch (stage) {
      case CREATED:
        picassoWeakReference = new WeakReference<>(Picasso.with(activity));
        break;
      case STOPPED:
        // Clean up reference
        picassoWeakReference = null;
        break;
      default: // NOP
    }
  }
}

USAGE

  @Before
  protected void setUp() throws Exception {
    super.setUp();
    
    Espresso.registerIdlingResources(mPicassoIdlingResource);

    ActivityLifecycleMonitorRegistry
            .getInstance()
            .addLifecycleCallback(mPicassoIdlingResource);
  }
  
  @After
  protected void tearDown() throws Exception {
    super.tearDown();
    
    Espresso.unregisterIdlingResources(mPicassoIdlingResource);
  }
@sebaslogen
Copy link

Hi, I forked this gist and updated it with a couple of improvements to handle multiple Activities and execute tests faster:
https://gist.github.com/sebaslogen/0b2fdea3f322c730e04b0af7285fcd28

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment