Get rid of arrow-effects usage
[dcaegen2/collectors/hv-ves.git] / sources / hv-collector-utils / src / main / kotlin / org / onap / dcae / collectors / veshv / utils / arrow / core.kt
index cb1c622..cfed7f3 100644 (file)
 package org.onap.dcae.collectors.veshv.utils.arrow
 
 import arrow.core.Either
+import arrow.core.ForOption
 import arrow.core.Option
 import arrow.core.Try
+import arrow.core.extensions.option.monad.monad
+import arrow.core.fix
 import arrow.core.identity
 import arrow.syntax.collections.firstOption
+import arrow.typeclasses.MonadContinuation
+import reactor.core.publisher.Flux
+import reactor.core.publisher.Mono
 import java.util.concurrent.atomic.AtomicReference
 
 /**
@@ -31,12 +37,23 @@ import java.util.concurrent.atomic.AtomicReference
  * @since July 2018
  */
 
+object OptionUtils {
+    fun <A> binding(c: suspend MonadContinuation<ForOption, *>.() -> A)
+            : Option<A> = Option.monad().binding(c).fix()
+}
+
 fun <A> Either<A, A>.flatten() = fold(::identity, ::identity)
 
 fun <B> Either<Throwable, B>.rightOrThrow() = fold({ throw it }, ::identity)
 
 fun <A, B> Either<A, B>.rightOrThrow(mapper: (A) -> Throwable) = fold({ throw mapper(it) }, ::identity)
 
+fun <A : Exception, B> Flux<Either<A, B>>.throwOnLeft(): Flux<B> = map { it.rightOrThrow() }
+
+fun <A, B> Flux<Either<A, B>>.throwOnLeft(f: (A) -> Exception): Flux<B> = map { it.rightOrThrow(f) }
+
+fun <A, B> Mono<Either<A, B>>.throwOnLeft(f: (A) -> Exception): Mono<B> = map { it.rightOrThrow(f) }
+
 fun <A> AtomicReference<A>.getOption() = Option.fromNullable(get())
 
 fun <A> Option.Companion.fromNullablesChain(firstValue: A?, vararg nextValues: () -> A?): Option<A> =
@@ -52,4 +69,18 @@ fun <A, B> Either<A, B>.doOnLeft(action: () -> Unit): Either<A, B> = apply { if
 
 fun <A> Option<A>.doOnEmpty(action: () -> Unit): Option<A> = apply { if (isEmpty()) action() }
 
-fun <A> Try<A>.doOnFailure(action: () -> Unit): Try<A> = apply { if (isFailure()) action() }
+fun <A> Try<A>.doOnFailure(action: (Throwable) -> Unit): Try<A> = apply {
+    if (this is Try.Failure) {
+        action(exception)
+    }
+}
+
+fun <A, B> A.mapBinding(c: suspend MonadContinuation<ForOption, *>.(A) -> B)
+        : Option<B> = let { OptionUtils.binding { c(it) } }
+
+
+
+
+
+
+