Failed to subscribe thenMany item

2019-03-02 05:39发布

问题:

When I use Mono.thenMany, the Flux data is lost, why?

@Test
fun thenManyLostFluxDataTest() {
  Mono.empty<Int>()
    .thenMany<Int> { Flux.fromIterable(listOf(1, 2)) }
    .subscribe { println(it) } // why not output item 1, 2
}

If I change to use blockLast() to do the subscribe, the test method run forever. So fearful:

@Test
fun thenManyRunForeverTest() {
  Mono.empty<Int>()
    .thenMany<Int> { Flux.fromIterable(listOf(1, 2)) }
    .blockLast() // why run forever
}

Now I use another way to do what the thenMany method should do:

// this method output item 1, 2
@Test
fun flatMapIterableTest() {
  Mono.empty<Int>()
    .then(Mono.just(listOf(1, 2)))
    .flatMapIterable { it.asIterable() }
    .subscribe { println(it) } // output item 1, 2 correctly
}ed

回答1:

You are using Kotlin's "lambda as a last parameter" short-form syntax. The thing is, if you look at the thenMany method signature, it doesn't accept a Function, but a Publisher.

So why is that lambda accepted, and what does it represent?

It seems to be in fact interpreted as a Publisher (as it has only 1 method, subscribe(Subscriber))!

Replace the { } with ( ) and everything will be back to normal.