我正在制作一个简单的recyclerview列表,其中包含从API返回的项目。我有我的改造客户
open class CoinListRetroFit {
val httpLoggingInterceptor = HttpLoggingInterceptor()
val okHttpClient = OkHttpClient.Builder()
.readTimeout(1000, TimeUnit.SECONDS)
.addInterceptor(httpLoggingInterceptor)
.build()
private val retroFit: Retrofit = Retrofit.Builder()
.baseUrl(" https://api.coinmarketcap.com/v2/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
val coinList: LuckyCoinApiService = retroFit.create(LuckyCoinApiService::class.java)
我有一个拨打电话的Api服务和客户
interface LuckyCoinApiService {
@GET("listings/")
fun getCoinListing() : Observable<CoinListResponse>
}
class LuckyCoinApiClient : CoinListRetroFit() {
fun getCoins(): Observable<List<CoinListItem>> =
coinList.getCoinListing().map { response ->
response.cryptoList
}
}
现在下面是我订阅可观察并填充我的列表的位置,但是它返回null,当我去调试时,它在上的Client类中崩溃coinList.getCoinListing
。我没有得到与网络通话有关的信息,这正是我的OkHttpClient Interceptor
目的。这是我订阅可观察...的地方
addDisposable(LuckyCoinApiClient()
.getCoins()
.compose(ObservableTransformer { upstream: Observable<List<CoinListItem>> ->
upstream
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
})
.subscribe({ response ->
list = response
adapter.addItems(list!!)
},
{ _ ->
Log.e("CoinListController", "Error retrieving list!!")
}))
}
fun addDisposable(disposable: Disposable) {
if (compositeDisposable == null) {
compositeDisposable = CompositeDisposable(disposable)
} else {
compositeDisposable!!.add(disposable)
}
}
关于发出这些请求的工作方式,我一定会有误解。以及如何正确设置日志记录拦截器
编辑:
添加Internet权限并对我的可观察对象进行一些更改后,.setLevel()
对拦截器进行操作。现在,我可以在LogCat中看到网络呼叫,并且列表显示预期的200 OK响应。
但是现在响应停止在
08-30 15:06:25.446 5214-5238/com.example.luckycoins D/OkHttp: "id": 3238,
08-30 15:06:25.446 5214-5238/com.example.luckycoins D/OkHttp: "name": "ABCC Token",
08-30 15:06:25.446 5214-5238/com.example.luckycoins D/OkHttp: "symbol": "AT",
08-30 15:06:25.446 5214-5238/com.example.luckycoins D/OkHttp: "website_slug": "abcc-token"
08-30 15:06:25.446 5214-5238/com.example.luckycoins D/OkHttp: },
08-30 15:06:25.446 5214-5238/com.example.luckycoins D/OkHttp: {
08-30 15:06:25.446 5214-5238/com.example.luckycoins D/OkHttp: "id": 3239,
它在id
不读取其属性的情况下停止。还有2-3个列表项,剩余的列表项没有达到。
您adapter.addItems(list!!)
在流阻止之外。您不应该通过副作用来更新用户界面。由于您的api请求将位于io线程池中的其他线程上,因此您的适配器很可能会在api调用完成之前使用空列表进行更新。
您应该做的是在subscribe({})
模块内更新适配器。
另外,您不应强制拆开可为空的列表。您应该在kotlin中执行的操作是像在Java中那样用null检查将其包装起来,或者像这样使用let运算符list?.let{ list ->}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句