根据价值减少助焊剂排放?

时间:2018-10-17 14:54:26

标签: kotlin project-reactor

我的通量如下:

val myFlux = Flux.fromIterable(listOf("A", "A", "B", "C", "C"))

此通量内的元素已排序,通量本身很大(我们可以假设它是无限的)

我想将其映射到Flux<String>,其中每个String分别包含AA B CC

也可以是Flux<SomeDomainObject>,其中每个SomeDomainObject将包含相同的键(例如AA

我不能使用groupBy,因为密钥数量很大。

所需的通量行为: desired flux behavior

2 个答案:

答案 0 :(得分:3)

您可以使用bufferUntil功能:https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#bufferUntil-java.util.function.Predicate-boolean-

fun<T> newItem(): Predicate<T> {
    var lastItem: T? = null

    return Predicate<T> { newItem ->
        when {
            lastItem == null -> {
                lastItem = newItem
                false
            }
            lastItem != newItem -> {
                lastItem = newItem
                true
            }
            else -> false
        }
    }
}

fun main(args: Array<String>) {
    val flux = Flux.just("A", "A", "B", "C", "C")
    val buffered = flux.bufferUntil(newItem(), true).map { it.joinToString("") }

    buffered.subscribe {
        println(it)
    }
}

答案 1 :(得分:0)

该代码段如何?

Flux<String> letters = Flux.just("A", "A", "A", "A", "B", "C", "C");
Flux<String> sequence = letters.bufferUntil(new Predicate<String>() {

        private AtomicReference<String> currentLetter = new AtomicReference<>("");

        @Override
        public boolean test(String letter) {
            String current = currentLetter.getAndSet(letter);
            return current.equals(letter);
        }
    }).map(list -> String.join("", list));