Building dependency graphs asynchronously in dagger 2

This is a more theoretical question. Please let me know if I go in the wrong direction.

Is there any way to load some graph dependencies asynchronously / in parallel in dagger 2? Should one even consider it in the context of a dagger?

My problem is mainly related to the launch time of the application. Many external dependencies, such as Mixpanel, Crashlytics / Fabric, Retrofit (RestAdapter), cause the application to warm up for longer than 1 second.

What helped me a lot was the Lazy <> interface, but the final effect still did not satisfy me.

Any ideas?

Example

The application has SplashActivity, which depends on the SplashActivityPresenter, which depends on: the Mixpanel, RestAdapter, and Crashlytics libraries (and several "smaller" objects). Each of them has a .init () method, which takes a lot of time (Mixpanel initialization takes about 200 ms on Nexus 5, Android M. Therefore, it will take about 2 seconds as a result before the user sees the Splash screen.

Is there a way to build these objects in parallel?

+7
android asynchronous dagger-2
source share
2 answers

Save the creation of the graph synchronously and postpone the creation of the object until it is signed with Rx defer. Downstream injections can be notified via Subject when an object is created.

@Module public static class AppModule{ @Provides @Singleton public Observable<A> provideA(){ return Observable.defer( () -> Observable.just(new A()) ); } } 

 public class MainActivity extends AppCompatActivity{ @Inject Observable<A> aObservable; A a; AppComponent appComponent; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); if(appComponent == null){ appComponent = ((App) getApplication()) .getAppComponent(); } appComponent.inject(this); aObservable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<A>(){ @Override public void call(final A aa){ a = aa; Log.d("MainActivity", "a = aa"); } }); } } 

Cautions: you must manually check the object! null or rely on an object acting as an eventbus, which will skip the logical state of the object on which objects located downstream should wait.

+6
source share

There is nothing special about creating a Dagger 2 graphic. If you want this done in the background thread, just call DaggerYourComponent.create() or DaggerYourComponent.Builder.build() in the background thread (use your preferred method for this - for example, AsyncTask).

If you have @Inject constructors that assume they will execute in the user interface thread, then you will have to modify them, but otherwise you should not have a problem.

+1
source share

All Articles