Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more Publisher extensions. #61

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/main/kotlin/reactor/kotlin/core/publisher/MonoExtensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package reactor.kotlin.core.publisher

import org.reactivestreams.Publisher
import reactor.core.publisher.Mono
import java.util.Optional
import java.util.concurrent.Callable
import java.util.concurrent.CompletableFuture
import java.util.function.Function
Expand Down Expand Up @@ -68,6 +69,20 @@ fun <T> CompletableFuture<out T?>.toMono(): Mono<T> = Mono.fromFuture(this)
*/
fun <T> Callable<T?>.toMono(): Mono<T> = Mono.fromCallable(this::call)

/**
* Extension for transforming a [Runnable] to a [Mono].
*
* @author Cyril Delmas
*/
fun <T> Runnable.toMono(): Mono<T> = Mono.fromRunnable(this)

/**
* Extension for transforming an [Optional] to a [Mono].
*
* @author Cyril Delmas
*/
fun <T> Optional<out T?>.toMono(): Mono<T> = Mono.justOrEmpty(this)

/**
* Extension for transforming an exception to a [Mono] that completes with the specified error.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import reactor.kotlin.test.verifyError
import reactor.test.StepVerifier
import reactor.test.publisher.TestPublisher
import java.io.IOException
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.CompletableFuture

Expand Down Expand Up @@ -164,6 +165,25 @@ class MonoExtensionsTests {
.verifyError(IllegalStateException::class)
}

@Test
fun optionalToMono() {
StepVerifier.create(Optional.of(42).toMono())
.expectNext(42)
.verifyComplete()
}

@Test
fun optionalEmptyToMono() {
StepVerifier.create(Optional.empty<Any>().toMono())
.verifyComplete()
}

@Test
fun runnableToMono() {
StepVerifier.create(Runnable { }.toMono<Any>())
.verifyComplete()
}

@Test
fun `cast() with generic parameter`() {
val monoOfAny: Mono<Any> = Mono.just("foo")
Expand Down