Skip to content

Instantly share code, notes, and snippets.

@dino-su
Last active July 14, 2019 13:37
Show Gist options
  • Save dino-su/7a161e952101a6983135af81656abbe6 to your computer and use it in GitHub Desktop.
Save dino-su/7a161e952101a6983135af81656abbe6 to your computer and use it in GitHub Desktop.
Missing Manuals: Waiting without Espresso idling resources.

Sample: Wait for Service

Wait loginComplete = new Wait() {
  @Override
  public Boolean apply() {
    return Service.isLogin() == true;
   }
};

Wait.until(loginComplete);

Sample: Wait for UI

Wait playlistUpdated = new Wait() {
  @Override
  public Boolean apply() {
    try {
      onView(withText("華語速爆新歌 (每週二五更新)")).check(matches(isDisplayed()));
    } catch (NoMatchingViewException e) {
      // keep waiting
      return false;
    }
    
    // complete
    return true;
  }
};

assertTrue(Wait.until(playlistUpdated));
import android.os.SystemClock;
public abstract class Wait {
public abstract Boolean apply();
public static Boolean until(WaitCondition condition) {
long startTime = SystemClock.uptimeMillis();
Boolean result = condition.apply();
for (long elapsedTime = 0; result == null || result.equals(false);
elapsedTime = SystemClock.uptimeMillis() - startTime) {
if (elapsedTime >= 2000) {
break;
}
SystemClock.sleep(500);
result = condition.apply();
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment