public static <X> X waitFor(Callable<X> until, long duration, TimeUnit in) {
    long end = System.currentTimeMillis() + in.toMillis(duration);

    X value = null;
    Exception lastException = null;

    while (System.currentTimeMillis() < end) {
      try {
        value = until.call();

        if (value instanceof Boolean) {
          if ((Boolean) value) {
            return value;
          }
        } else if (value != null) {
          return value;
        }

        sleep(100);
      } catch (Exception e) {
        // Swallow for later re-throwing
        lastException = e;
      }
    }

    if (lastException != null) {
      throw propagate(lastException);
    }

    throw new RuntimeException("Condition timed out: " + until);
  }
Wait for the callable to return either "not null" or "true". Exceptions are caught and only
rethrown if we time out.

@param until Condition that we're waiting for.
@param duration How long to wait.
@param in Unit in which duration is measured.
@return Whatever the condition returns.
selendroid-client/src/main/java/io/selendroid/client/waiter/TestWaiter.java