为什么Dagger2中的异步依赖注入不起作用?

时间:2017-10-05 21:46:51

标签: android dagger-2 rx-java2

我在方法中有依赖注入,这很慢,这就是原因 我尝试将依赖项注入异步,但它无法正常工作。 我在featuredCalendar()中有一些日志,它打印日志" step1" 但是没有打印" step2"

@Singleton 
@Provides 
fun apiDaysSeResource(retrofit: Retrofit): Observable<ApiDaysSeResource{ 
return Observable.create(ObservableOnSubscribe<ApiDaysSeResource> { 
retrofit.create<ApiDaysSeResource>(ApiDaysSeResource::class.java) 
}).subscribeOn(Schedulers.io()) 
.observeOn(AndroidSchedulers.mainThread()) 
}

public interface ApiDaysSeResource {
@GET("dagar.json?")
Single<FeaturedCalendar> days(@Query("fran") String fran, @Query("till") String till, @Query("key") String key, @Query("id") String id);
}



@Singleton
@Provides
 fun vacationRepository(apiDaysSeResource: Observable<ApiDaysSeResource>): VacationRepository {
return VacationRepository(apiDaysSeResource)


 }




class VacationRepository(private val apiDaysSeResource: Observable<ApiDaysSeResource>) {
fun featuredCalendar(from: String, till: String, key: String, id: String): Flowable<FeaturedCalendar> {
Log.i("time_test", " step1")
return apiDaysSeResource.flatMapSingle { apiDaysSeResource ->
  Log.i("time_test", " step2")
  apiDaysSeResource.days(from, till, key, id)
}.toFlowable(BackpressureStrategy.BUFFER)
  }
}

1 个答案:

答案 0 :(得分:0)

我解决了我的问题,我做了一些小改动 并且还看一下这个样本 https://github.com/frogermcs/Dagger2Recipes-AsyncInjection

@Singleton
@Provides
fun apiDaysSeResource(retrofit:Retrofit):ApiDaysSeResource{
return retrofit.create(ApiDaysSeResource::class.java)}

 @Singleton
@Provides
fun  apiDaysSeResourceObservable(apiDaysResource: Lazy<ApiDaysSeResource>): Observable<ApiDaysSeResource> {
return Observable.defer { Observable.just(apiDaysResource.get()) }
  }