With Retrofit's RxJava 3 adapter, how do create(), createSynchronous() and createWithScheduler() differ, and why can subscribeOn have no effect?
answer
- async by default since adapter-rxjava3
- enqueue versus execute underneath
- OkHttp threads, not your scheduler
- observeOn for the main thread
basics
~20 sRxJava3CallAdapterFactory.create() enqueues each call on OkHttp's threads, so subscribeOn does not change where it runs. createSynchronous() executes on the subscribing thread, and createWithScheduler() executes on the given scheduler. None of them moves results to the main thread; observeOn does.
solid answer
~40 s`RxJava3CallAdapterFactory.create()` builds asynchronous types: on subscribe it clones the call and `enqueue()`s it, so the request runs on OkHttp's dispatcher threads and a `subscribeOn(...)` upstream changes nothing. `createSynchronous()` uses `execute()` on whichever thread subscribes, which is where `subscribeOn(Schedulers.io())` matters; `createWithScheduler(scheduler)` does the same with that scheduler applied by default. None of them moves results to the main thread: the adapter bypasses Retrofit's Android callback executor, so with `create()` results arrive on an OkHttp thread and the UI needs `observeOn(AndroidSchedulers.mainThread())`. Every subscription clones the call, so a re-subscription or `retry()` sends a new request, and disposing cancels it. The async default is new with the RxJava 3 adapter, added in Retrofit 2.9.0: the RxJava 1 and 2 adapters' `create()` was synchronous.
code
kotlin · 33 linesimport io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.kotlinx.serialization.asConverterFactory
import retrofit2.create
import retrofit2.http.GET
@Serializable
data class Profile(val id: Long, val name: String)
interface ProfileApi {
@GET("me")
suspend fun me(): Profile // the coroutine repository layer
@GET("me")
fun meRx(): Single<Profile> // the older RxJava 3 screen
}
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build()
fun loadProfile(render: (Profile) -> Unit, showError: (Throwable) -> Unit): Disposable =
retrofit.create<ProfileApi>().meRx()
.observeOn(AndroidSchedulers.mainThread()) // create() emits on an OkHttp thread
.subscribe({ render(it) }, { showError(it) })go deeper
Recall that RxJava return types need adapter-rxjava3 registered with addCallAdapterFactory, and that results need observeOn to reach the main thread.
Explain create versus createSynchronous versus createWithScheduler in terms of enqueue versus execute, and why subscribeOn does nothing for create().
Reason about cold, one-shot semantics: each subscription clones the call, retry resends a POST, disposal cancels the OkHttp call and suppresses the late error.
Weigh keeping an RxJava screen on the same Retrofit instance as the coroutine layer against migrating it, given that both styles can share one service interface.
## Adding the adapter RxJava return types are not built into Retrofit. The artifact `com.squareup.retrofit2:adapter-rxjava3` provides `RxJava3CallAdapterFactory`, which you register with `Retrofit.Builder.addCallAdapterFactory()`. Service methods can then return `Observable<T>`, `Flowable<T>`, `Single<T>`, `Maybe<T>` or `Completable` from `io.reactivex.rxjava3.core`. One Retrofit instance can serve both styles at once: a repository layer can call `suspend` methods while an older screen subscribes to a `Single` from the same interface, because suspend methods are looked up as `Call<T>`, which the RxJava factory declines. ## The three factory methods | Factory method | What happens on subscribe | Where the HTTP call runs | Effect of `subscribeOn` | |---|---|---|---| | `create()` | clones the call and `enqueue()`s it | OkHttp's dispatcher threads | none on the request | | `createSynchronous()` | clones the call and `execute()`s it | the subscribing thread | decides the thread | | `createWithScheduler(scheduler)` | like `createSynchronous()`, with `subscribeOn(scheduler)` applied | that scheduler | already applied by default | The factory's own documentation states it directly: with `create()`, "applying `subscribeOn(..)` has no effect". The request is asynchronous by construction, so an upstream `subscribeOn(Schedulers.io())` only moves the act of subscribing. With `createSynchronous()` and no `subscribeOn`, the HTTP call blocks the thread that subscribed; if that is Android's main thread, the platform refuses the network access. ## Where the result arrives - The RxJava adapter is a **custom return type**, so Retrofit's callback executor, the main-thread hop that `Call.enqueue()` gets on Android, does **not** apply. - With `create()` the value or error is emitted on an OkHttp thread; with the synchronous variants it is emitted on the thread that executed the call. - To touch views, add `observeOn(AndroidSchedulers.mainThread())` from RxAndroid downstream of the Retrofit type. - `subscribeOn` and `observeOn` themselves, and scheduler choice in general, are covered in the lesson on RxJava. ## What the type parameter means | Declaration | Emits | Signals an error for | |---|---|---| | `Single<User>` | the body of a 2xx response | a non-2xx status (`HttpException`) and network failures (`IOException`) | | `Single<Response<User>>` | every HTTP response | network failures only | | `Single<Result<User>>` | a `retrofit2.adapter.rxjava3.Result` for every outcome | nothing; the error sits inside `Result` | | `Completable` | completion, body discarded | a non-2xx status and network failures | The `HttpException` the adapter raises is a subclass of `retrofit2.HttpException`; the adapter's own `retrofit2.adapter.rxjava3.HttpException` class is deprecated in favour of the core one, so catch the core type. ## Subscription, retry and disposal Retrofit's RxJava types are **cold**: nothing happens until someone subscribes, and each subscriber triggers its own request. 1. On subscribe, the adapter **clones** the one-shot `Call`, so every subscription is a fresh HTTP request. 2. A second subscriber, a `retry()` or a `repeat()` therefore sends the request again rather than replaying a result. 3. `dispose()` sets a flag and calls `cancel()` on that cloned `Call`, which cancels the OkHttp call underneath. 4. After disposal the adapter drops a late failure instead of delivering it, so a disposed screen does not get an error. Sharing one response between several subscribers needs an RxJava sharing operator, not a second subscription. ## Common mistakes - Adding `subscribeOn(Schedulers.io())` to every Retrofit chain out of habit and believing it controls the request thread under `create()`. - Forgetting `observeOn` and touching views from an OkHttp thread, which the Android view system rejects because only the main thread may touch views. - Subscribing twice to one `Single`, for example from two observers, and being surprised by two requests. - Not keeping the `Disposable`, so the request and its callbacks outlive the screen. - Registering the RxJava 2 adapter while declaring RxJava 3 types; each adapter only recognises its own major version's types. ## Version notes - The RxJava 3 adapter arrived in Retrofit 2.9.0. Its `create()` is asynchronous, a deliberate change from the RxJava 1 and RxJava 2 adapters, whose `create()` produced synchronous types and needed `createAsync()` for the enqueue behaviour. - Retrofit 2.10.0 removed backpressure support from the RxJava 2 and 3 adapters, because a Retrofit call emits a single value. - RxJava 3 lives in `io.reactivex.rxjava3`; the RxJava 2 adapter, `adapter-rxjava2`, targets the older `io.reactivex` packages and is a different artifact.
- Why does adding retry(2) to a Retrofit Single send up to three HTTP requests?Retrofit's RxJava types are cold and the adapter clones the one-shot `Call` on every subscription. `retry()` re-subscribes after an error, so each attempt is a brand-new request. That is usually what you want for a GET, but for a non-idempotent POST it can repeat a side effect on the server.
- What happens to the HTTP request when the screen disposes a Retrofit Single that is still in flight?Disposing calls `cancel()` on the cloned `Call`, which cancels the OkHttp call underneath. The adapter then suppresses the resulting failure instead of calling `onError`, so the disposed observer sees nothing. A request the server already received may still have been processed there.
- When would you choose createWithScheduler(Schedulers.io()) or createSynchronous() over create()?When you want the HTTP call itself to run on a scheduler you choose instead of OkHttp's dispatcher: `createWithScheduler()` applies that scheduler to every call by default, and `createSynchronous()` lets each chain pick one with `subscribeOn`, or run on the test thread in a unit test. `create()` is the simpler default, because OkHttp's dispatcher already manages concurrency.
- With RxJava3CallAdapterFactory.create(), subscribeOn(Schedulers.io()) moves the HTTP call to the io scheduler.
- Retrofit delivers RxJava results on the main thread, like Call callbacks.
- A Retrofit Single caches its response, so retry() reuses it.
- RxJava 3's create() is synchronous, just like the RxJava 2 adapter's.
- Single<User> emits a value even for an HTTP 404.
Assumes Retrofit 3.0.0 with adapter-rxjava3 (added in 2.9.0), whose create() is asynchronous, unlike the RxJava 1 and RxJava 2 adapters' create().