SolvedRxJava Get RxCachedThreadScheduler-n when calling Disposable.dispose()

Requirement

I migrate from 1.x to 2.x, replace Subscription to Disposable, and I'd like to cancel the subscription before a new subscription starts. But I got RxCachedThreadScheduler-n when calling Disposable.dispose(). I've check #4807 and found that it may timeout problem, but I'm sure that my api is pretty fast and won't be timeout at all. How can I resolve this problem??

Exception

E/AndroidRuntime: FATAL EXCEPTION: RxCachedThreadScheduler-1
                  Process: com.machipopo.swag, PID: 30241
                  java.io.InterruptedIOException: thread interrupted
                      at okio.Timeout.throwIfReached(Timeout.java:145)
                      at okio.Okio$2.read(Okio.java:136)
                      at okio.AsyncTimeout$2.read(AsyncTimeout.java:211)
                      at okio.RealBufferedSource.request(RealBufferedSource.java:71)
                      at okio.RealBufferedSource.require(RealBufferedSource.java:64)
                      at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.java:270)
                      at okhttp3.internal.http.Http1xStream$ChunkedSource.readChunkSize(Http1xStream.java:441)
                      at okhttp3.internal.http.Http1xStream$ChunkedSource.read(Http1xStream.java:422)
                      at okio.RealBufferedSource.read(RealBufferedSource.java:50)
                      at okio.RealBufferedSource.exhausted(RealBufferedSource.java:60)
                      at okio.InflaterSource.refill(InflaterSource.java:101)
                      at okio.InflaterSource.read(InflaterSource.java:62)
                      at okio.GzipSource.read(GzipSource.java:80)
                      at okio.RealBufferedSource.request(RealBufferedSource.java:71)
                      at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:225)
                      at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:187)
                      at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160)
                      at okhttp3.RealCall.execute(RealCall.java:57)
                      at com.test.api.ApiService.get(ApiService.java:145)
                      at com.test.UserApi$1.subscribe(UserApi.java:63)

Old 1.x Code

if (mSubscriptionLoadMe != null && !mSubscriptionLoadMe.isUnsubscribed()) 
	mSubscriptionLoadMe.unsubscribe();
mSubscriptionLoadMe = UserApi.getUserInfo(this, userId)
		.subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Subscriber<String>() {
			onNext();
			onCompleted();
			onError();
		});

New 2.x Code

if (mSubscriptionLoadMe != null && !mSubscriptionLoadMe.isDisposed())
	mSubscriptionLoadMe.dispose();
mSubscriptionLoadMe = UserApi.getUserInfo(this, userId)
		.subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribeWith(new DisposableObserver<String>() {
			onNext();
			onCompleted();
			onError();
		});
21 Answers

✔️Accepted Answer

@crazyhitty looks like you have an Observable.create() around the okhttp blocking call. You have to check for cancellation before emitting any error if you don't want to receive such errors:

Observable.create(emitter -> {
    // ...
    try {
         responsebody.string();
    } catch (InterruptedException ex) {
        if (!emitter.isDisposed()) {
            emitter.onError(ex);
            return;
        }
    }
})

Other Answers:

@don11995 If you don't care about such exceptions then you can suppress them via:

RxJavaPlugins.setErrorHandler(Functions.<Throwable>emptyConsumer());

@crazyhitty since version 2.1.1 tryOnError is available:

The emitter API (such as FlowableEmitter, SingleEmitter, etc.) now features a new method, tryOnError that tries to emit the Throwable if the sequence is not cancelled/disposed. Unlike the regular onError, if the downstream is no longer willing to accept events, the method returns false and doesn't signal an UndeliverableException.

https://github.com/ReactiveX/RxJava/blob/2.x/CHANGES.md

Related Issues:

154
RxJava How to keep an Observable alive after onError?
The pattern for this abersnaze is referring to is (swallowing all errors (I'm learning reactive) My ...
52
RxJava 3.x: Potential migration/compatibility issues
After careful considerations of all target environments (Android/Desktop/Server) as well as any futu...
24
RxJava Get RxCachedThreadScheduler-n when calling Disposable.dispose()
@crazyhitty looks like you have an Observable.create() around the okhttp blocking call ...
167
prettier Change HTML/JSX formatting to have one attribute/prop per line
The point I am trying to make is that the vertical space matters Wasting it (too much) has negative ...
105
prettier [resolved] [HTML] allow corresponding option to jsxBracketSameLine
I don't think I've ever seen any markup language with the closing brackets on a separate line I'd li...
90
prettier Feature Request: breakBeforeElse
This feels like one of those I can't adopt prettier unless options that was mentioned in the 1.0 rel...
87
prettier Add option to omit semicolons in output
I use standard.js which is a popular no-configuration style guide & linter They insist on a semicolo...
72
apollo tooling 2.12.3: Error: Cannot use GraphQLSchema "[object GraphQLSchema]" from another module or realm
If you are using npm: Copy the version of graphql from your node_modules/apollo/package.json For me ...
72
prettier Space after function name in declarations
This is one of the reasons I've had to step away from adopting Prettier I would be quite happy with ...
69
prettier Ugly line break in a template string
Maybe templates should never be wrapped because it looks ugly most of time This input looks better t...
63
prettier Space after function keyword in anonymous functions
+1 for space after function keyword Crockford supports this: If a function literal is anonymous ...
59
prettier Break on multiple chained calls
Could we manage chains like we manage object literals in that if they have a break within them they ...
56
prettier Respect paren + newline
I've made a PR that: Adds wrapping parens back to JSX Arrow functions (when the JSX is multiline): U...
50
prettier Prettier 2.0 – 2.0 2020
@lydell you fogot Change the default for singleQuote to true We already have a Prettier 2.0 issue – ...
39
prettier Option to add parenthesis to multiline expressions
Just because an arrow function is multiline doesn't necessarily make it complex and call for using {...
33
apollo tooling Why does codegen:generate require query names to be unique?
This is now a closed issue so I'm not sure it is worth to comment it again It makes no sense ...
31
flow typed react-redux type error when only passing in only mapStateToProps on flow v0.55.0
Annotating mapStateToProps has worked for me Flow infers what version of connect to use this way. ...
22
apollo tooling error: Validation of GraphQL query document failed
I think the confusion here is that some people (myself included) want typescript interfaces for all ...
22
prettier Allow inline method chaining if line length does not exceed printWidth
There are many popular patterns chaining method calls using enzyme Just to give you some context on ...
21
prettier Typescript cannot parse // inside of JSX
@Kuzmenkoar Until the bug is fixed I think this is the nicest workaround: I'm having a problem with ...
19
flow typed "Invalid Version: undefined" semver on version 3.x flow-typed
You can also pin using yarn resolutions in package.json https://classic.yarnpkg.com/en/docs/selectiv...
19
prettier RxJS pipe chaining get formatted on a single line
I agree with @yannickglt As a developer it's much easier to reason about an RxJS pipeline if every s...
17
prettier [1.6] Tracking issue
I just fixed all the issues I could find running it through the fb codebase and understood what was ...
16
apollo tooling Strategy for @client directive
Support for the @client directive with client-side schemas has been released with Apollo CLI 1.4.0! ...
15
prettier Support TypeScript 4.0
Also a catch clause can legally have a type now (only : any and : unknown are allowed) - today Prett...
13
prettier Long curried function calls
As I've said I am not sure if there is a more ideal way to reformat this Prettier changed this: to t...
13
prettier Pug plugin doesn't work for the .vue files
👋 @prettier/core team! I may have found a hint for people wanting to use @prettier/plugin-pug and V...
13
prettier Change arrowParens to always by default for 2.0
I always set arrowParens to always in my personal projects Why i think we need to change that? code ...
12
apollo tooling Cannot convert undefined or null to object
This is an example of usage of schema:download and client:codegen: #671 (comment) For schema:downloa...
12
flow typed Error: flow_v0.38.x <=v0.52.x: Unexpected trailing characters: <=v0.52.x
rm -rf flow-typed && flow-typed update works for me We started getting this error when running flow-...
12
prettier Support for .html.eex files?
I quite enjoy prettier and I would love to have it supported for .html.eex files Agreed with the dis...
12
prettier Feature request: Twig support
I’ve been looking into this as well for Django Templates As @allejo mentions there are a lot of temp...
11
prettier [RFC] Editor Integration
Been mentioned already but I would push for using something such as cosmiconfig which implements the...
7
apollo tooling VSCode commands not found: extension not loading correctly?
Also having issues and I just followed @trevor-scheer advice to delete the extension folder and rein...
5
prettier Format untagged GraphQL template literals preceded by /* GraphQL */
Fwiw a trick I've loved is const gql = String.raw Gets prettier editor support and typeahead with no...
3
flow typed Express definition file
@export-mike not sure if this is the perfect solution but we declare a global class that extends exp...
360
pgjdbc org.postgresql.jdbc.PgConnection.createClob() is not yet implemented
@mkpaz The property hibernate.jdbc.lob.non_contextual_creation works you just need to use it like th...
189
springfox @ApiModelProperty throwing NumberFormatException if example value is not set
Hi everybody I solved this issue removing old swagger version (1.5.20) and add new one In pom.xml ...
180
elasticsearch es crashes with "Native controller process has stopped - no new native processes can be started"
@martin-g Did you find it out? having the same issue Update: setting: - discovery.type=single-node s...
173
retrofit Kotlin & @Body
You can still use Map just suppress its wildcardness with @JvmSuppressWildcards ...
158
dbeaver "invalid privatekey" connecting through SSH tunnel
Run this on your key to convert it to RSA private key Helped me ssh-keygen -p -m PEM -f ~/.ssh/id_rs...
152
junit5 java.lang.NoSuchMethodError: org.junit.platform.commons.util.ReflectionUtils.tryToLoadClass Migrating to 5.4.0
Fixed by replacing: with: JDK: 11 Spring Boot: 2.1.2.RELEASE JUnit: 5.4.0 Maven: 3.6.0 Surefire: 3.0...
133
flutter intellij Can't wrap widget list with new widget assist by Alt+Enter
@wisit-phusi I thought you may disable Dart Quick Assists (Alt+Enter) from IDE To make sure please o...
127
idea gitignore All files are marked as ignored
All right fix has been released with v3.1.2 Now it has to be accepted by the Jetbrains team. ...
126
capacitor FileReader API not firing
You can try this. Description of the problem: In my project I'm trying to read and convert a Blob do...
121
springfox Swagger ui stuck on unable to infer base url
I had the same problem using Spring Boot 2.0.0.M4 + Spring Security This solved my issue: I don't kn...
105
springfox Issue when using Swagger latest version 2.9.2 with Spring boot 2.2.0
Added this to dependency and it worked for me. Hi ...
101
generator jhipster Uncaught Error: Module build failed: Error: ENOENT: no such file or directory, scandir '**\node_modules\node-sass\vendor'
@lancurtis run npm rebuild node-sass Hi There was an error occured in my chrome on windows 10 x64 wh...
92
cordova android Build errors about drawable since upgrading to v8.0.0
Hello all ! This error also appears when I do release build after upgrading to cordva-android@8.0.0 ...