RxJava2 +在数据请求时改装黑屏
我正在尝试使用RxJava2和Retrofit2(在Kotlin中)检索某些Api数据时遇到了Android应用程序的问题。 一旦我执行呼叫,屏幕变黑,应用程序不再响应,没有任何日志消息。
我正在使用的通话url如下:
api/apartments?projection={"id":1,"address":1}
这个调用的服务接口是这样的:
@GET("api/apartments?projection={\"id\":1,\"address\":1}") fun getAllApartments(@Header(AUTHORIZATION) auth: String): Single<List>
这是我执行呼叫的方式:
override fun getAllApartments(): Single<List> = retrofit.create(ApartmentsService::class.java).getAllApartments("$BEARER$token")
这就是我所说的function:
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" } ]
我想你正在主线程中进行网络调用。 奇怪的是,你只是得到像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