繁体   English   中英

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

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

在Dagger中,您必须注入UI线程。 运行JUnit时,您不在UI线程上运行。 为了使其工作,我们必须在UI线程上发布一个Runnable并等待其完成注入。

我的代码如下所示:

    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);
        }
    }

问题在于,当调用latch.await()时,myRunnable无法启动。 在运行JUnit时,使Dagger注入的最佳方法是什么?

暂无
暂无

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

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