aboutsummaryrefslogtreecommitdiff
path: root/README.md
blob: 075aee433140c004a2c7e6825fdaf1f45b7e2bed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# Fibers for Scala

This library implements **fibers** (or **coroutines**) on top of
delimited continuations as provided by the [Scala CPS compiler
plugin][continuations].

## Usage

In your `build.sbt` file:

```scala
// Enable CPS plugin
addCompilerPlugin("org.scala-lang.plugins" % "scala-continuations-plugin_2.12.2" % "1.0.3"),
libraryDependencies += "org.scala-lang.plugins" %% "scala-continuations-library" % "1.0.3",
scalacOptions += "-P:continuations:enable",

// Depend on fibers-core
resolvers += Resolver.bintrayRepo("mulk", "maven")
libraryDependencies ++= Seq(
  "eu.mulk" %% "fibers-core" % "0.1.0",
)
```

## Examples

Awaiting futures and tasks and emitting values:

```scala
import monix.eval.Task
import monix.execution.Scheduler.Implicits.global
import monix.reactive.Observable

import eu.mulk.fibers.Fiber._

import scala.util.Success

val slowBackgroundTask = Task.delay(100)

def produceNumbers: Unit @fiber[Int] = {
  val Success(x) = await(slowBackgroundTask)
  emit(x)
  emit(x*2)
  emit(x*3)
}

val observable: Observable[Int] = run(produceNumbers)
observable.foreachL(println).runAsync  // => 100, 200, 300
```

Using fiber-local state:

```scala
import monix.eval.Task
import monix.execution.Scheduler.Implicits.global
import monix.reactive.Observable

import eu.mulk.fibers.Fiber._

def emitFiberVar: Unit @fiber[Int] = {
  emit(getFiberVar)
}

def produceNumbers: Unit @fiber[Int] = {
  putFiberVar[Int](100)
  emitFiberVar
}

val observable: Observable[Int] = run(produceNumbers)
observable.foreachL(println).runAsync  // => 100
```

For more examples, see the [unit tests][].

[continuations]: https://github.com/scala/scala-continuations
[unit tests]:    core/t/FiberSpec.scala