改造+ RxJava未发出API请求

时间:2019-09-22 11:06:33

标签: android kotlin retrofit2 rx-java2

我在Kotlin中有Retrofit和RxJava2的问题。

这是我的build.gradle

// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.6.1' implementation 'com.squareup.retrofit2:converter-moshi:2.6.1'
implementation 'com.squareup.okhttp3:okhttp:4.2.0'
implementation 'com.squareup.moshi:moshi-kotlin:1.8.0'

// RxJava
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.11'

我具有以下带有单个请求login的Retrofit接口。我还有一个简单的data class,名为User

data class User (
    private val firstName: String
)

interface ApiService {
    @POST("auth/login")
    fun login(@Body body: String) : Observable<User>
}

当我尝试发出请求并订阅该请求时,没有发送请求。我已经检查了服务器日志,但服务器根本没有收到任何信息。应用日志中也没有错误。我不确定自己在做什么错,因为我看过很多文章/教程,他们都说这样做。

val client = Retrofit.Builder()
    .baseUrl("https://example.com/api/")
    .addCallAdapterFactory(RxJava2CallAdapaterFactory.create())
    .build()
    .create(ApiService::class.java)

client.login(JSONObject().put("email", ...).toString())
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe()

有人可以向我解释我实际上在做错什么吗?

编辑:

我尝试了以下代码,但仍得到相同的结果。没有请求。

val okHttpClient = OkHttpClient.Builder().addInterceptor(
    HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT)
).build()

val client = Retrofit.Builder()
    .baseUrl("https://example.com/api/")
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .client(okHttpClient)
    .build()
    .create(ApiClient::class.java)

client.login(JSONObject().put("email", ...).toString())
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({ user -> println(user) }, { error -> println(error) })

2 个答案:

答案 0 :(得分:1)

您缺少将Moshi转换器添加到改造实例中的机会。

.addConverterFactory(MoshiConverterFactory.create())

答案 1 :(得分:0)

您应该添加一个日志拦截器以查看日志。

val httpClient = OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .build()

val builder = Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(RxJava2CallAdapaterFactory.create())  

val apiService = builder.client(httpClient).build().create(ApiService::class.java)

我假设您向AndroidManifest.xml添加了INTERNET权限

正如@sonnet所建议的,您应该在请求中添加回调

apiService.login(JSONObject().put("email", ...).toString())
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({ user -> ... }, { error -> ... })
相关问题