Skip to content

Instantly share code, notes, and snippets.

@aahlenst
Last active July 27, 2021 15:56
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save aahlenst/8d3958ceceb971465873e5818ba6fd1f to your computer and use it in GitHub Desktop.
Save aahlenst/8d3958ceceb971465873e5818ba6fd1f to your computer and use it in GitHub Desktop.
IdlingResource that makes Espresso 2 wait until all RxJava 2 tasks have finished
/*
* The MIT License
*
* Copyright (c) 2016 Andreas Ahlenstorf
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
public class RxIdlingResource implements IdlingResource, Function<Runnable, Runnable> {
private static final String RESOURCE_NAME = RxIdlingResource.class.getSimpleName();
private static final ReentrantReadWriteLock IDLING_STATE_LOCK = new ReentrantReadWriteLock();
// Guarded by IDLING_STATE_LOCK
private int taskCount = 0;
// Guarded by IDLING_STATE_LOCK
private ResourceCallback transitionCallback;
@Override
public String getName() {
return RESOURCE_NAME;
}
@Override
public boolean isIdleNow() {
boolean result;
IDLING_STATE_LOCK.readLock().lock();
result = taskCount == 0;
IDLING_STATE_LOCK.readLock().unlock();
return result;
}
@Override
public void registerIdleTransitionCallback(final ResourceCallback callback) {
IDLING_STATE_LOCK.writeLock().lock();
this.transitionCallback = callback;
IDLING_STATE_LOCK.writeLock().unlock();
}
@Override
public Runnable apply(final Runnable runnable) throws Exception {
return new Runnable() {
@Override
public void run() {
IDLING_STATE_LOCK.writeLock().lock();
taskCount++;
IDLING_STATE_LOCK.writeLock().unlock();
try {
runnable.run();
} finally {
IDLING_STATE_LOCK.writeLock().lock();
try {
taskCount--;
if (taskCount == 0 && transitionCallback != null) {
transitionCallback.onTransitionToIdle();
}
} finally {
IDLING_STATE_LOCK.writeLock().unlock();
}
}
}
};
}
}
@aahlenst
Copy link
Author

Usage:

RxIdlingResource rxIdlingResource = new RxIdlingResource();
Espresso.registerIdlingResources(rxIdlingResource);
RxJavaPlugins.setScheduleHandler(rxIdlingResource);

@LuigiPapino
Copy link

Just modified a bit, because wasn't working for me.
I don't use it with espresso for now, but in unit tests running with the AndroidJUnit.

the problem for me was, that the taskCount was increased in the returned Runnable, so the resource was busy only while executing the task.
I wanted the resource to be busy from the instant the task is scheduled.

I also added an utility method that just wait until the resource is idle, so can be used in unit tests.

/*
 * The MIT License
 *
 * Copyright (c) 2016 Andreas Ahlenstorf
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

import android.support.test.espresso.IdlingResource;
import com.adaptics.dropkitchen.utils.Loggy;
import io.reactivex.functions.Function;
import io.reactivex.plugins.RxJavaPlugins;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RxIdlingResource implements IdlingResource, Function<Runnable, Runnable> {

  private static final String TAG = RxIdlingResource.class.getSimpleName();

  private static final ReentrantReadWriteLock IDLING_STATE_LOCK = new ReentrantReadWriteLock();

  // Guarded by IDLING_STATE_LOCK
  private int taskCount = 0;

  // Guarded by IDLING_STATE_LOCK
  private ResourceCallback transitionCallback;

  @Override
  public String getName() {
    return TAG;
  }

  @Override
  public boolean isIdleNow() {

    boolean result;

    IDLING_STATE_LOCK.readLock().lock();
    result = taskCount == 0;
    IDLING_STATE_LOCK.readLock().unlock();

    return result;
  }

  @Override
  public void registerIdleTransitionCallback(final ResourceCallback callback) {
    IDLING_STATE_LOCK.writeLock().lock();
    this.transitionCallback = callback;
    IDLING_STATE_LOCK.writeLock().unlock();
  }

  @Override
  public Runnable apply(final Runnable runnable) throws Exception {
    IDLING_STATE_LOCK.writeLock().lock();
    taskCount++;
    Loggy.d(TAG, "TaskCount increase " + taskCount);
    IDLING_STATE_LOCK.writeLock().unlock();
    return () -> {
      try {
        runnable.run();
      } finally {
        IDLING_STATE_LOCK.writeLock().lock();

        try {
          taskCount--;
          Loggy.d(TAG, "TaskCount decrease " + taskCount);

          if (taskCount == 0 && transitionCallback != null) {
            transitionCallback.onTransitionToIdle();
            Loggy.d(TAG, "idle ");
          }
        } finally {
          IDLING_STATE_LOCK.writeLock().unlock();
        }
      }
    };
  }

  public void waitForIdle() {
    if (!isIdleNow()) {
      CountDownLatch latch = new CountDownLatch(1);
      registerIdleTransitionCallback(latch::countDown);
      try {
        latch.await();
      } catch (InterruptedException e) {
        Loggy.e(TAG, e.getMessage(), e);
      }
    }
  }

  public void register() {
    RxJavaPlugins.setScheduleHandler(this);
  }
}

Just init in the setup

 RxIdlingResource rxIdlingResource = new RxIdlingResource();
  @Before
  public void setUp() throws Exception {
    rxIdlingResource = new RxIdlingResource();
    rxIdlingResource.register();
  }

And use it in the test:

@Test
public void testCool(){

   usecase.executeFetchAndSave(); //background task with retrofit and rxjava
   rxIdlingResource.waitForIdle();

  //your assertions
}

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