Android Espresso-等待异步加载 [英] Android Espresso - wait for asynchronous load

查看:318
本文介绍了Android Espresso-等待异步加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RecyclerView,数据被异步加载到其中.

I have a RecyclerView into which data is loaded asynchronously.

基础引擎不使用AsyncTasks,而是使用Java Executor.

The underlying engine does not use AsyncTasks, but java Executor.

如何使Espresso在超时之前等待(或定期检查),直到满足给定条件?

我已经阅读了有关IdlingResource的信息,但在我看来,这似乎是逐例进行的深入研究,其中可能存在一些通用的东西,这些东西可能会定期检查条件,直到满足条件或发生超时.

I've read about IdlingResource, but it seems to me like digging too deep, on a case-by-case basis, where there could exist something general-purpose, that could periodically check for a condition, until it is fulfilled or timeout happens.

难道不是每隔几百毫秒检查一次是否满足条件吗?无需深入研究内部工作原理... 那会是性能问题吗?

Couldn't it just check, every few-hundred milliseconds, if the condition is met? Without the need to delve into the inner workings... Would that be a performance problem?

推荐答案

您可以使用诸如waitFor方法之类的东西.

You can use something like a waitFor method.

public class WaitAction implements ViewAction {

  /** The amount of time to allow the main thread to loop between checks. */

  private final Matcher<View> condition;
  private final long timeoutMs;

  public WaitAction(Matcher<View> condition, long timeout) {
    this.condition = condition;
    this.timeoutMs = timeout
  }

  @Override
  public Matcher<View> getConstraints() {
    return (Matcher) anything();
  }

  @Override
  public String getDescription() {
    return "wait";
  }

  @Override
  public void perform(UiController controller, View view) {
    controller.loopMainThreadUntilIdle();
    final long startTime = System.currentTimeMillis();
    final long endTime = startTime + timeoutMs;

    while (System.currentTimeMillis() < endTime) {
      if (condition.matches(view)) {
        return;
      }

      controller.loopMainThreadForAtLeast(100);
    }

    // Timeout.
    throw new PerformException();
  }

  public static ViewAction waitFor(Matcher<View> condition, long timeout) {
    return new WaitAction(condition, timeout);
  }
}

您可以按以下方式使用

onView(<some view matcher>).perform(WaitAction.waitFor(<Some condition>));

这篇关于Android Espresso-等待异步加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆