RxJava 2

Arrow aims to enhance the user experience when using RxJava. While providing other datatypes that are capable of handling effects, like IO, the style of programming encouraged by the library allows users to generify behavior for any existing abstractions.

One of these abstractions is RxJava, a library focused on providing composable streams that enable reactive programming. Observable streams are created by chaining operators into what are called observable chains.

Observable.from(7, 4, 11, 3)
  .map { it + 1 }
  .filter { it % 2 == 0 }
  .scan { acc, value -> acc + value }
//[8, 20, 24]

Integration with your existing Observable chains

The largest quality of life improvement when using Observables in Arrow is the introduction of the Monad Comprehension. This library construct allows expressing asynchronous Observable sequences as synchronous code using binding/bind.

Arrow Wrapper

To wrap any existing Observable in its Arrow Wrapper counterpart, you can use the extension function k().

import arrow.fx.rx2.*
import io.reactivex.*
import io.reactivex.subjects.*

val obs = Observable.fromArray(1, 2, 3, 4, 5).k()
// ObservableK(observable=io.reactivex.internal.operators.observable.ObservableFromArray@6589c3dd)
val flow = Flowable.fromArray(1, 2, 3, 4, 5).k()
// FlowableK(flowable=io.reactivex.internal.operators.flowable.FlowableFromArray@3b232d94)
val single = Single.fromCallable { 1 }.k()
// SingleK(single=io.reactivex.internal.operators.single.SingleFromCallable@7d0d1572)
val maybe = Maybe.fromCallable { 1 }.k()
// MaybeK(maybe=io.reactivex.internal.operators.maybe.MaybeFromCallable@8cf13d3)
val subject = PublishSubject.create<Int>().k()
// ObservableK(observable=io.reactivex.subjects.PublishSubject@17edb591)

You can return to their regular forms using the function value().

// io.reactivex.internal.operators.observable.ObservableFromArray@6589c3dd
// io.reactivex.internal.operators.flowable.FlowableFromArray@3b232d94
// io.reactivex.internal.operators.single.SingleFromCallable@7d0d1572
// io.reactivex.internal.operators.maybe.MaybeFromCallable@8cf13d3
// io.reactivex.subjects.PublishSubject@17edb591

Support for suspend functions

Arrow adds a new constructor effect that allows using suspend functions with Observable, Single, and Flowable.

suspend fun sideEffect(): Unit = println("Hello!")
ObservableK.async().effect {
SingleK.async().effect {
FlowableK.async().effect {

Observable comprehensions

The library provides instances of MonadError and MonadDefer.

Async allows you to generify over datatypes that can run asynchronous code. You can use it with ObservableK, FlowableK, or SingleK.

fun <F> getSongUrlAsync(MS: MonadDefer<F>) =
  MS { getSongUrl() }

val songObservable: ObservableKOf<Url> = getSongUrlAsync(ObservableK.monadDefer())
val songFlowable: FlowableKOf<Url> = getSongUrlAsync(FlowableK.monadDefer())
val songSingle: SingleKOf<Url> = getSongUrlAsync(SingleK.monadDefer())
val songMaybe: MaybeKOf<Url> = getSongUrlAsync(MaybeK.monadDefer())

Monad can be used to start a Monad Comprehension using the method fx, with all its benefits.

Let’s take an example and convert it to a comprehension. We’ll create an observable that loads a song from a remote location, and then reports the current play % every 100 milliseconds until the percentage reaches 100%:

  .map { songUrl -> MediaPlayer.load(songUrl) }
  .flatMap {
    val totalTime = musicPlayer.getTotaltime()
    Observable.interval(100, Milliseconds)
      .flatMap {
        Observable.create { musicPlayer.getCurrentTime() }
          .map { tick -> (tick / totalTime * 100).toInt() }
      .takeUntil { percent -> percent >= 100 }

When rewritten using fx it becomes:

import arrow.fx.rx2.*
import arrow.fx.rx2.extensions.fx
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import java.util.concurrent.TimeUnit

ObservableK.fx {
  val (songUrl) = getSongUrlAsync()
  val musicPlayer = MediaPlayer.load(songUrl)
  val totalTime = musicPlayer.getTotaltime()

  val end = PublishSubject.create<Unit>()
  !Observable.interval(100, TimeUnit.MILLISECONDS).takeUntil(end).k()

  val tick = !delay(UI) { musicPlayer.getCurrentTime() }
  val percent = (tick / totalTime * 100).toInt()
  if (percent >= 100) {


Note that any unexpected exception, like ArithmeticException when totalTime is 0, is automatically caught and wrapped inside the observable.

Subscription and cancellation

Observables created with comprehensions like fx behave the same way regular observables do, including cancellation by disposing the subscription.

val disposable =
    .subscribe({ Log.d("Song $it") } , { println("Error $it") })


Stack safety

While MonadDefer usually guarantees stack safety, this does not apply for the rx2 wrapper types. This is a limitation on rx2’s side. See the corresponding github issue.

To overcome this limitation and run code in a stack in a safe way, one can make use of fx.stackSafe which is provided for every instance of Monad when you have arrow-free included.

import arrow.Kind
import arrow.fx.rx2.FlowableK
import arrow.fx.rx2.ForFlowableK
import arrow.fx.rx2.fix
import arrow.fx.rx2.extensions.flowablek.monad.monad
import arrow.free.stackSafe

fun main() {
  // This will not result in a stack overflow
  val result = FlowableK.monad().fx.stackSafe {
    (1..50000).fold(just(0)) { acc: Kind<ForFlowableK, Int>, x: Int ->
      just(acc.bind() + 1)
import arrow.Kind
import arrow.fx.IO
import arrow.fx.rx2.*
import arrow.fx.rx2.extensions.flowablek.monad.monad

// This will result in a stack overflow

IO {
  FlowableK.monad().fx.monad {
    (1..50000).fold(just(0)) { acc: Kind<ForFlowableK, Int>, x: Int ->
      just(acc.bind() + 1)
// Left(java.lang.StackOverflowError)

Do you like Arrow?

Arrow Org