Project Reactor

intermediate

Arrow aims to enhance the user experience when using Project Reactor. 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 such abstractions is Project Reactor, a library that, like RxJava, offers reactive streams.

val flux = Flux.just(7, 4, 11 ,3)
    .map { it + 1 }
    .filter { it % 2 == 0 }
    .scan { acc, value -> acc + value }
    .collectList()
    .subscribeOn(Schedulers.parallel())
    .block()
//[8, 20, 24]

Integration with your existing Flux chains

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

Arrow Wrapper

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

import arrow.effects.*
import reactor.core.publisher.*

val flux = Flux.just(1, 2, 3, 4, 5).k()
flux
// FluxK(flux=FluxArray)
val mono = Mono.just(1).k()
mono
// MonoK(mono=MonoJust)

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

flux.value()
// FluxArray
mono.value()
// MonoJust

Observable comprehensions

The library provides instances of MonadError and MonadDefer.

MonadDefer allows you to generify over datatypes that can run asynchronous code. You can use it with FluxK or MonoK.

fun <F> getSongUrlAsync(MS: MonadDefer<F>) =
  MS { getSongUrl() }
  
val songFlux: FluxKOf<Url> = getSongUrlAsync(FluxK.monadDefer())
val songMono: MonoKOf<Url> = getSongUrlAsync(MonoK.monadDefer())

MonadError can be used to start a Monad Comprehension using the method bindingCatch, 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%:

getSongUrlAsync()
  .map { songUrl -> MediaPlayer.load(songUrl) }
  .flatMap {
    val totalTime = musicPlayer.getTotaltime()
    Flux.interval(Duration.ofMillis(100))
      .flatMap {
        Flux.create { musicPlayer.getCurrentTime() }
          .map { tick -> (tick / totalTime * 100).toInt() }
      }
      .takeUntil { percent -> percent >= 100 }
  }

When rewritten using bindingCatch it becomes:

import arrow.effects.*
import arrow.typeclasses.*

ForFluxK extensions {
  bindingCatch {
    val songUrl = getSongUrlAsync().bind()
    val musicPlayer = MediaPlayer.load(songUrl)
    val totalTime = musicPlayer.getTotaltime()
    
    val end = DirectProcessor.create<Unit>()
    Flux.interval(Duration.ofMillis(100)).takeUntilOther(end).bind()
    
    val tick = musicPlayer.getCurrentTime().bind()
    val percent = (tick / totalTime * 100).toInt()
    if (percent >= 100) {
      end.onNext(Unit)
    }
    
    percent
  }.fix()
}

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

Subscription and cancellation

Flux streams created with comprehensions like bindingCatch behave the same way regular flux streams do, including cancellation by disposing the subscription.

val disposable =
  songFlux.value()
    .subscribe({ println("Song $it") }, { System.err.println("Error $it") })
    
disposable.dispose()

Note that MonadDefer provides an alternative to bindingCatch called bindingCancellable returning a arrow.Disposable. Invoking this Disposable causes an BindingCancellationException in the chain which needs to be handled by the subscriber, similarly to what Deferred does.

import arrow.effects.instances.defferred.monad.*

val (flux, disposable) =
  bindingCancellable {
    val userProfile = Flux.create { getUserProfile("123") }
    val friendProfiles = userProfile.friends().map { friend ->
        bindDefer { getProfile(friend.id) }
    }
    listOf(userProfile) + friendProfiles
  }

flux.value()
    .subscribe({ println("User $it") }, { System.err.println("Boom! caused by $it") })
    
disposable()
// Boom! caused by BindingCancellationException

Supported Type Classes

Module Type classes
arrow.effects.typeclasses Async, Bracket, ConcurrentEffect, Effect, MonadDefer
arrow.typeclasses ApplicativeError, Applicative, Foldable, Functor, MonadError, Monad, MonadThrow, Traverse