Skip to content

Commit f41388c

Browse files
committed
chore: Stream Gatherers example
1 parent acf8db1 commit f41388c

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

shared/src/jsMain/kotlin/dev/suresh/http/HttpClient.js.kt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,5 @@ actual fun httpClient(
1111
httpLogger: KLogger,
1212
config: HttpClientConfig<*>.() -> Unit
1313
) = HttpClient(Js) { config(this) }
14+
15+
fun getKtorEnvLogLevel(): String? = js("process.env.KTOR_LOG_LEVEL")
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package dev.suresh;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.function.BiConsumer;
6+
import java.util.function.Function;
7+
import java.util.function.Supplier;
8+
import java.util.stream.Gatherer;
9+
import java.util.stream.Gatherer.Downstream;
10+
import java.util.stream.Gatherer.Integrator;
11+
import java.util.stream.Stream;
12+
13+
public class Gatherers {
14+
15+
static <T, R> Gatherer<T, ?, R> map(Function<T, R> f) {
16+
Integrator<Void, T, R> integrator = (_, e, ds) -> {
17+
var ir = f.apply(e);
18+
return ds.push(ir);
19+
};
20+
return Gatherer.of(integrator);
21+
}
22+
23+
static <T> Gatherer<T, List<T>, List<T>> group(int size) {
24+
Supplier<List<T>> initializer = ArrayList::new;
25+
Integrator<List<T>, T, List<T>> integrator = (list, e, ds) -> {
26+
list.add(e);
27+
if (list.size() < size) {
28+
return true;
29+
} else {
30+
var group = List.copyOf(list);
31+
list.clear();
32+
return ds.push(group);
33+
}
34+
};
35+
BiConsumer<List<T>, Downstream<? super List<T>>> finisher = (list, ds) -> {
36+
var group = List.copyOf(list);
37+
if (!group.isEmpty()) {
38+
ds.push(group);
39+
}
40+
};
41+
return Gatherer.ofSequential(initializer, integrator, finisher);
42+
}
43+
44+
public static void main(String[] args) {
45+
Stream.of(1, 2, 3, 4, 5).gather(map(e -> e + 1)).gather(group(2)).forEach(System.out::println);
46+
}
47+
}
48+
49+

0 commit comments

Comments
 (0)