【发布时间】:2017-10-23 14:39:12
【问题描述】:
您好,我正在尝试学习 rxjava2。我正在尝试使用 rxjava2 调用 API,并使用改造来构建 URL 并将 JSON 转换为 Moshi。
我想将Observable 模式与retrofit 一起使用。有谁知道怎么做?任何标准和最佳方法,例如用于错误处理的包装器等等?
AppModule.kt
@Provides
@Singleton
fun provideRetrofit(moshi: Moshi, okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BuildConfig.BASE_URL)
.client(okHttpClient)
.build()
}
ApiHelperImpl.kt
@Inject
lateinit var retrofit: Retrofit
override fun doServerLoginApiCall(email: String, password: String): Observable<LoginResponse> {
retrofit.create(RestApi::class.java).login(email, password)
}
我正在从LoginViewModel 拨打doServerLoginApiCall,如下所示
LoginViewModel.kt
fun login(view: View) {
if (isEmailAndPasswordValid(email, password)) {
ApiHelperImpl().doServerLoginApiCall(email, password)
}
}
RestApi.kt
interface RestApi {
@FormUrlEncoded
@POST("/partner_login")
fun login(@Field("email") email: String, @Field("password") password: String): Call<LoginResponse>
}
LoginResponse.kt
data class LoginResponse(
@Json(name = "code")
val code: Int? = null,
@Json(name = "otp_verify")
val otpVerify: Int? = null,
@Json(name = "data")
val userDetails: UserDetails? = null,
@Json(name = "message")
val message: String? = null,
@Json(name = "status")
val status: String? = null
)
【问题讨论】:
-
你到底有什么问题?
-
@Watcharin.s 在我的案例中使用 rxjava2 以及如何将结果发送回视图模型是一种新的有点困惑的方式
-
你可以查看我的仓库:github.com/savepopulation/wikilight
标签: android kotlin retrofit2 rx-java2