将dagger2与Retrofit和MVVM一起使用

时间:2019-07-30 10:31:54

标签: java android kotlin mvvm dagger-2

我正在尝试在我的应用中使用DaggerRetrofitVMMV结构,但是在这种情况下我不知道如何使用Retrofit。我有模块和接口,可以在其中实现对API的调用。我以前使用过Dagger,我认为我应该有一个组件将ApiCalls与我想使用它的MainViewModel连接起来。我的方式正确吗?如果不是,我应该如何与我的ViewModel绑定以获得具有凭据的Observable

我的NetworkModule

@Module
object NetworkModule{

    /**
     * Provides the Post service implementation.
     * @param retrofit the Retrofit object used to instantiate the service
     * @return the Post service implementation.
     */
    @Provides
    @Reusable
    @JvmStatic
    fun provideUserAuth(retrofit: Retrofit): ApiCredentials{
        return retrofit.create(ApiCredentials::class.java)
    }

    /**
     * Provides the Retrofit object.
     * @return the Retrofit object
     */
    val provideRetrofit: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
    }
}

我的ApiCalls进行了改装:

interface ApiCredentials {

    @get:POST("/api/auth/sign_in")
    val getAuthentication: Observable<Credentials>
}

我的MainViewModel

class MainViewModel : ViewModel() {
    // TODO: Implement the ViewModel
}

1 个答案:

答案 0 :(得分:0)

您可以建立存储库,以在构造函数中获取接口的引用,并通过一种方法可以在repo中访问api。

class ApiRepository @Inject constructor(
private val apiCredentials: ApiCredentials
) {
 fun hitApi():Observable<Credentials>{
 return apiCredentials.getAuthentication
 }
}

在视图模型中,您可以通过注射器之类的对象来获得该回购的对象

@Inject
protected lateinit var repo: ApiRepository

在视图模型中,您可以使用它。

相关问题