我在尝试使用RxJava2和Retrofit2(在Kotlin中)检索一些Api数据时遇到了Android应用程序的问题。一旦我执行了呼叫,屏幕就会变黑,应用程序就不再响应了,没有任何日志消息。
我正在使用的通话网址如下:
api/apartments?projection={"id":1,"address":1}
此次通话的服务界面如下:
@GET("api/apartments?projection={\"id\":1,\"address\":1}")
fun getAllApartments(@Header(AUTHORIZATION) auth: String): Single<List<APTLIST>>
这是我执行呼叫的方式:
override fun getAllApartments(): Single<List<APTLIST>> = retrofit.create(ApartmentsService::class.java).getAllApartments("$BEARER$token")
这就是我调用函数的方式:
getAllApartmentsUseCase.getAllApartments()
.subscribe(
{
apartments.clear()
apartments.addAll(it)
view.showApartments(apartments)
},
{ println(it.message) }
)
此调用适用于Postman,结果如下:
[
{
"_id": "591ecaca861a528a5b4c3d90",
"id": "ROC 03"
},
{
"_id": "591a0fb2861a528a5b4c3d60"
},
{
"_id": "58be94d484c4b0a468fb93e0",
"id": "CAN 2.3",
"address": "Els Refugis"
}
]
答案 0 :(得分:0)
我猜你是在主线程中进行网络通话。奇怪的是,你得到像ANR而不是android.os.NetworkOnMainThreadException。
getAllApartmentsUseCase
.getAllApartments()
.subscribeOn(Schedulers.io()) //scheduler in which observable will execute
.observeOn(AndroidSchedulers.mainThread()) //scheduler in which subscriber's methods will be called
.subscribe(/*subscriber*/)
https://medium.com/upday-devs/rxjava-subscribeon-vs-observeon-9af518ded53a