Skip to content

Commit 9f4e460

Browse files
committed
add async doc
1 parent 50af4a2 commit 9f4e460

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

build.mill

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//| mill-version: 1.0.4
1+
//| mill-version: 1.0.5
22
//| mill-jvm-version: 21
33
//| mvnDeps:
44
//| - io.github.quafadas:millSite_mill1_3.7:0.0.53

site/docs/cookbook/async.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Async
2+
3+
One situation for me is enriching table data from an external source, that is perhaps a network call away.
4+
5+
Making all those calls in sequence can be slow...
6+
7+
But it we call the `addColumn` method on an already materialised collection... we can get async behaviour. The strategy below works, but is naive... useful for a quick and dirty
8+
9+
```scala mdoc
10+
11+
import io.github.quafadas.table.*
12+
import scala.concurrent._
13+
import scala.concurrent.duration._
14+
import ExecutionContext.Implicits.global
15+
16+
val data = CSV.fromString("id\n1\n2\n3").toSeq
17+
18+
def slowNetworkFetch(id: String) = {
19+
blocking {
20+
Thread.sleep(1000)
21+
s"The Answer $id"
22+
}
23+
}
24+
25+
println(
26+
data
27+
.addColumn["answer", Future[String]](
28+
row =>
29+
Future(slowNetworkFetch(row.id))
30+
)
31+
.mapColumn["answer", String](Await.result(_, Duration.Inf))
32+
.consoleFormatNt(fansi = false)
33+
)
34+
```
35+
36+
If we want something more "idiomatic" in terms of `Future` handling, we can drop down into our knowledge of stdlib, traverse, map, zip and join...
37+
38+
```scala mdoc
39+
40+
val d2 = data
41+
.addColumn["answer_tmp", Future[String]](
42+
row =>
43+
Future(slowNetworkFetch(row.id))
44+
)
45+
46+
val resolved = Await.result(Future.traverse(d2.column["answer_tmp"])(identity), Duration.Inf)
47+
48+
println(
49+
d2.zip(resolved).map{ (row, res) =>
50+
row ++ (answer = res)
51+
}
52+
.dropColumn["answer_tmp"]
53+
.consoleFormatNt(fansi = false)
54+
)
55+
```

0 commit comments

Comments
 (0)