Async view query hangs under strange conditions


#1

Here is a example of code to reproduce the bug:
asyncbucket.get("29035") .map((JsonDocument t3) -> { ViewQuery query = ViewQuery.from("random","view"); asyncbucket .query(query) .flatMap(AsyncViewResult::rows) .count() .toBlocking() .single(); return null; }) .count() .toBlocking() .single()

(do not look at how hugly the code is, it’s just to highlight the bug).

Issue: https://issues.couchbase.com/browse/JCBC-897


#2

As discussed in the JIRA ticket, the problem was in mixing blocking and non-blocking code (blocking inside a map/flatMap).

The code above is a simplification but the call to toBlocking().single() inside the map is problematic.

In the real code, there was a need for creating an Observable out of a blocking method call.
When absolutely unavoidable, such a call must be done in the correct threading context (eg. Schedulers.io()) by chaining observeOn(Schedulers.io()) before the .map.

Note that the rest of the processing will then also be done in the threads from the io pool, so you may want to revert back to another threading context using observeOn later on.

Schedulers.newThread() can also be used, but io is able to reuses threads using a thread pool.

The real code uses a flatMap(x -> Observable.create(...)). Another possibility in this case is to chain a .subscribeOn(Schedulers.io()) after the create(...), inside the flatMap.