Rx features

part of kovenant-rx

Addon project for converting back and forth between Kovenant Promises and rx Observables.


Any Observable can be turned into a Promise but understand that there is a fundamental difference between the two. A Promise represents a single value that either is successful or failed. An Observable on the other hand represents a stream of values which results in the following possible states:

To convert from an Observable to a Promise you simply do:

val values = arrayOf(1, 2, 3, 4, 5)
val observable = Observable.from(values)
val promise = observable.toPromise()

By default toPromise() will create a promise that will resolve successful with the first emitted value. It will resolve as failed if there are no values emitted but the Observable emits completed. This will thus lead to:


By default toPromise() resolves successful with the first emitted value. If you'd rather resolve by the last emitted value you can change the behaviour by calling:

val promise = observable.toPromise(strategy = EmitStrategy.LAST)


By default toPromise() resolves as failed if the Observable is completed but hasn't emitted a value. To control the behaviour of the promise when the Observable is empty you can create one of the following EmptyPolicies:

//resolve with value
EmptyPolicy.resolve (42)

//resolve with factory value
EmptyPolicy.resolve { 42 }

//reject with eception

//reject with exception factory
EmptyPolicy.reject { Exception() }

And you can use them like this:

val promise = observable.toPromise(emptyPolicy = EmptyPolicy.resolve (42))

There is also a shorthand for this common case, so you can always resolve successful with a default value:

val promise = observable.toPromise(42)
//or with a factory
val promise = observable.toPromise() { 42 }


Instead of converting an Observable to a single value we can also simply put al te results in a List. This is as simple as:

val promise = observable.toListPromise()

The only requirement for this to work is that the Observable actually emits completed at some point in the future.


To turn a Promise into an Observable you can simply call toObservable(). Note that by default the Observable is observed on the callback Dispatcher of the Promise in question.