Flowable
Explore how to use Flowable in RxJava to manage backpressure when processing streams with higher emission rates. Understand different backpressure strategies, when to choose Flowable over Observable, and how to implement buffering for efficient reactive data handling in Android applications.
We'll cover the following...
A scenario
Say that, when given a list of image files, we needed to load each image file to memory and apply a CPU-bound function .processBitmap(), which takes some time to compute.
The above code should be fairly straightforward:
- First, a list of image files is converted into an
Observable<File>. - Using
.map(), each emission from that stream is then decoded into a bitmap, which produces anObservable<Bitmap>. - The bitmap stream is then zipped with an integer stream (or
Observable.range(1, imageFiles.length)) and combined as aPair. - Each decoded bitmap is then printed on
Logcat. - Finally, in the
.subscribe()function, each bitmap is processed via a long operation.processBitmap(). A thread sleep of 300 milliseconds is performed to simulate this.
Can you guess what might be produced when running the above code?
Backpressure
To solve the issue, we need a way to notify upstream that it should slow down its production until the consumer downstream can keep up with processing items.
The mechanism by which we can notify upstream that it should slow down its production is called backpressure. However, by using an Observable, we cannot apply backpressure because Observable objects are ...