简体   繁体   中英

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. When running JUnit you are not running on the UI-thread. In order to make it work we have to post a Runnable on the UI-thread and wait for it to finish inject.

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(). What is the best way to make Dagger to inject when running the JUnit?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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