简体   繁体   English

如何在ui线程上注入并等待注入完成才能继续?

[英]How to inject on the ui-thread and wait for the injection to finish before continue?

In Dagger you have to inject on the UI-thread. 在Dagger中,您必须注入UI线程。 When running JUnit you are not running on the UI-thread. 运行JUnit时,您不在UI线程上运行。 In order to make it work we have to post a Runnable on the UI-thread and wait for it to finish inject. 为了使其工作,我们必须在UI线程上发布一个Runnable并等待其完成注入。

My code looks like this: 我的代码如下所示:

    public void inject(final Object object) {
        // We always has to inject on the main thread.
        final CountDownLatch latch = new CountDownLatch(1);
        Handler mainHandler = new Handler(FodoApplication.getAppContext().getMainLooper());
        Runnable myRunnable = new Runnable() {
            public void run() {
                objectGraph.inject(object);
            latch.countDown();
            }
        };
        mainHandler.post(myRunnable);
        try {
            latch.await();
        } catch (InterruptedException e) {
            Log.e(TAG, "", e);
        }
    }

The problem is that myRunnable do not start when whe call latch.await(). 问题在于,当调用latch.await()时,myRunnable无法启动。 What is the best way to make Dagger to inject when running the JUnit? 在运行JUnit时,使Dagger注入的最佳方法是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM