Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Future<void> into RxJava Observable or Flowable

How do I convert a future returning void into an RxJava Flowable or Observable?

I am using RxJava and AndroidX WorkManager which provides an API which returns a Future<void>. I understand RxJava does not handle null values and will NullPointerException immediately. I am using Flowable.fromFuture(resultFuture), where resultFuture is Future<Void> (specifically ListenableFuture<Void>), but since it returns Null, it crashes the app.

Motivation: I want to turn this future into a Rx observable/ flowable so that I can do processing after this future completes.

        return Flowable.fromFuture(futureReturningVoid)
                .flatMap { Flowable.fromIterable(files) }
                ...more processing here...

I need to return a Single at the end, so I cannot move the work into a listener, with Future.addListener.


I need flowable because I am dealing with processing of multiple input files, and want the backpressure to prevent opening too many files at once. I included Observable in case people have less complex requirements.

like image 204
Ben Butterworth Avatar asked Apr 14 '26 12:04

Ben Butterworth


1 Answers

So why not :

return Completable.fromFuture(futureReturningVoid)
            .andThen(Flowable.fromIterable(files))

Which is basically :

return Completable.fromAction { futureReturningVoid.get() }
            .andThen(Flowable.fromIterable(files))
like image 72
Mark Avatar answered Apr 17 '26 01:04

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!