使用rxjava在非主线程上进行Retrofit2反序列化/转换 [英] Retrofit2 deserialization / conversion on non-main thread using rxjava

查看:208
本文介绍了使用rxjava在非主线程上进行Retrofit2反序列化/转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经提到过这个答案,它似乎与Retrofit v1有关。

I've referred to this answer already and it seems to be related to Retrofit v1.

目标 - >
通过使ObjectMapper在非主线程上工作来减少冷启动时间。 此图片显示主线程上发生的堆栈跟踪。

Goal -> To reduce cold start time by making ObjectMapper work on non-main thread. This image shows a stack trace of it happening on the main thread.

设置:

compile "com.squareup.retrofit2:retrofit:2.1.0"
compile "com.squareup.retrofit2:converter-jackson:2.1.0"
compile "com.squareup.retrofit2:adapter-rxjava:2.1.0"
compile 'io.reactivex:rxjava:1.1.9'

这是改装的配置

.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
.addConverterFactory(JacksonConverterFactory.create(ObjectMapperFactory.getObjectMapper()))

以下是拨打网络电话的典型示例

Below is a typical example of making a network call

compatibilityService().isCompatible()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> { ...});

JacksonConverterFactory 对象映射似乎在主线程上工作。

Within the JacksonConverterFactory the objectmapping seems to work on the main thread.

没有离开RxJava的解决方案是什么?

可能相关的帖子

  • Retrofit2.0 using with rxjava will do costly reflection in mian thread even using subscribeOn()
  • https://github.com/ReactiveX/RxJava/issues/4347

推荐答案

我没有使用Retrofit 1.x,但是在v2中你可以将返回类型定义为 RESP onse object(即 Observable< Response< SomeSerializableObject>> 而不是 Observable< SomeSerializableObject> )..这样,反序列化不应该发生,直到用户调用 .body()方法。这样,您可以通过 observeOn 运算符修改流,以便在 map 运算符中对指定的调度程序进行反序列化,例如。

I didn't use Retrofit 1.x, but in v2 you can define return type as Response object ( i.e. Observable<Response<SomeSerializableObject>> instead of Observable<SomeSerializableObject> ) .. in this way, the deserialization shouldn't happen until user calls .body() method on it. This way, you can modify the stream through observeOn operator so that it deserializes on your specified Scheduler within map operator for example.

我不能保证它在Retrofit 1.x中的可能性,但你应该能够轻松地研究它。

I can't guarantee that its possible in Retrofit 1.x as well, but you should be able to research that easily.

这篇关于使用rxjava在非主线程上进行Retrofit2反序列化/转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆