/
Task.scala
1981 lines (1840 loc) · 72.9 KB
/
Task.scala
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2014-2017 by The Monix Project Developers.
* See the project homepage at: https://monix.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monix.eval
import cats.effect.{Effect, IO}
import monix.eval.instances._
import monix.eval.internal._
import monix.execution.ExecutionModel.{AlwaysAsyncExecution, BatchedExecution, SynchronousExecution}
import monix.execution._
import monix.execution.atomic.Atomic
import monix.execution.cancelables.StackedCancelable
import monix.execution.internal.Platform
import monix.execution.misc.{NonFatal, ThreadLocal}
import scala.annotation.unchecked.{uncheckedVariance => uV}
import scala.collection.generic.CanBuildFrom
import scala.collection.mutable
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{ExecutionContext, Future, Promise, TimeoutException}
import scala.util.{Failure, Success, Try}
/** `Task` represents a specification for a possibly lazy or
* asynchronous computation, which when executed will produce an `A`
* as a result, along with possible side-effects.
*
* Compared with `Future` from Scala's standard library, `Task` does
* not represent a running computation or a value detached from time,
* as `Task` does not execute anything when working with its builders
* or operators and it does not submit any work into any thread-pool,
* the execution eventually taking place only after `runAsync` is
* called and not before that.
*
* Note that `Task` is conservative in how it spawns logical threads.
* Transformations like `map` and `flatMap` for example will default
* to being executed on the logical thread on which the asynchronous
* computation was started. But one shouldn't make assumptions about
* how things will end up executed, as ultimately it is the
* implementation's job to decide on the best execution model. All
* you are guaranteed is asynchronous execution after executing
* `runAsync`.
*
* =Getting Started=
*
* To build a `Task` from a by-name parameters (thunks), we can use
* [[Task.eval]] or [[Task.apply]]:
*
* {{{
* val hello = Task.eval("Hello ")
* val world = Task("World!")
* }}}
*
* Nothing gets executed yet, as `Task` is lazy, nothing executes
* until you trigger [[Task.runAsync(implicit* .runAsync]] on it.
*
* To combine `Task` values we can use [[Task.map .map]] and
* [[Task.flatMap .flatMap]], which describe sequencing and this time
* it's in a very real sense because of the laziness involved:
*
* {{{
* val sayHello = hello
* .flatMap(h => world.map(w => h + w))
* .map(println)
* }}}
*
* This `Task` reference will trigger a side effect on evaluation, but
* not yet. To make the above print its message:
*
* {{{
* import monix.execution.CancelableFuture
*
* val f: CancelableFuture[Unit] = sayHello.run()
* //=> Hello World!
* }}}
*
* The returned type is a
* [[monix.execution.CancelableFuture CancelableFuture]] which
* inherits from Scala's standard [[scala.concurrent.Future Future]],
* a value that can be completed already or might be completed at
* some point in the future, once the running asynchronous process
* finishes. Such a future value can also be canceled, see below.
*
* =Laziness=
*
* The fact that `Task` is lazy whereas `Future` is not
* has real consequences. For example with `Task` you can do this:
*
* {{{
* def retryOnFailure[A](times: Int, source: Task[A]): Task[A] =
* source.recoverWith { err =>
* // No more retries left? Re-throw error:
* if (times <= 0) Task.raise(err) else {
* // Recursive call, yes we can!
* retryOnFailure(times - 1, source)
* // Adding 500 ms delay for good measure
* .delayExecution(500)
* }
* }
* }}}
*
* `Future` being a strict value-wannabe means that the actual value
* gets "memoized" (means cached), however `Task` is basically a function
* that can be repeated for as many times as you want. `Task` can also
* do memoization of course:
*
* {{{
* task.memoize
* }}}
*
* The difference between this and just calling `runAsync()` is that
* `memoize()` still returns a `Task` and the actual memoization
* happens on the first `runAsync()` (with idempotency guarantees of
* course).
*
* But here's something else that the `Future` data type cannot do:
*
* {{{
* task.memoizeOnSuccess
* }}}
*
* This keeps repeating the computation for as long as the result is a
* failure and caches it only on success. Yes we can!
*
* ==Parallelism==
*
* Because of laziness, invoking [[Task.sequence]] will not work like
* it does for `Future.sequence`, the given `Task` values being
* evaluated one after another, in ''sequence'', not in ''parallel''.
* If you want parallelism, then you need to use [[Task.gather]] and
* thus be explicit about it.
*
* This is great because it gives you the possibility of fine tuning the
* execution. For example, say you want to execute things in parallel,
* but with a maximum limit of 30 tasks being executed in parallel.
* One way of doing that is to process your list in batches:
*
* {{{
* // Some array of tasks, you come up with something good :-)
* val list: Seq[Task[Int]] = ???
*
* // Split our list in chunks of 30 items per chunk,
* // this being the maximum parallelism allowed
* val chunks = list.sliding(30, 30)
*
* // Specify that each batch should process stuff in parallel
* val batchedTasks = chunks.map(chunk => Task.gather(chunk))
* // Sequence the batches
* val allBatches = Task.sequence(batchedTasks)
*
* // Flatten the result, within the context of Task
* val all: Task[Seq[Int]] = allBatches.map(_.flatten)
* }}}
*
* Note that the built `Task` reference is just a specification at
* this point, or you can view it as a function, as nothing has
* executed yet, you need to call
* [[Task.runAsync(implicit* .runAsync]] explicitly.
*
* =Cancellation=
*
* The logic described by an `Task` task could be cancelable,
* depending on how the `Task` gets built.
*
* [[monix.execution.CancelableFuture CancelableFuture]] references
* can also be canceled, in case the described computation can
* be canceled. When describing `Task` tasks with `Task.eval` nothing
* can be cancelled, since there's nothing about a plain function
* that you can cancel, but we can build cancelable tasks with
* [[Task.async]] (alias [[Task.create]]):
*
* {{{
* import scala.concurrent.duration._
*
* val delayedHello = Task.async { (scheduler, callback) =>
* val task = scheduler.scheduleOnce(1.second) {
* println("Delayed Hello!")
* // Signaling successful completion
* callback(Success(()))
* }
*
* Cancelable { () => {
* println("Cancelling!")
* task.cancel()
* }
* }
* }}}
*
* The sample above prints a message with a delay, where the delay
* itself is scheduled with the injected `Scheduler`. The `Scheduler`
* is in fact an implicit parameter to `runAsync()`.
*
* This action can be cancelled, because it specifies cancellation
* logic. In case we have no cancelable logic to express, then it's
* OK if we returned a
* [[monix.execution.Cancelable.empty Cancelable.empty]] reference,
* in which case the resulting `Task` would not be cancelable.
*
* But the `Task` we just described is cancelable:
*
* {{{
* // Triggering execution
* val f: CancelableFuture[Unit] = delayedHello.run()
*
* // If we change our mind before the timespan has passed:
* f.cancel()
* }}}
*
* Also, given an `Task` task, we can specify actions that need to be
* triggered in case of cancellation:
*
* {{{
* val task = Task.eval(println("Hello!")).executeWithFork
*
* task.doOnCancel(Task.eval {
* println("A cancellation attempt was made!")
* }
*
* val f: CancelableFuture[Unit] = task.run()
*
* // Note that in this case cancelling the resulting Future
* // will not stop the actual execution, since it doesn't know
* // how, but it will trigger our on-cancel callback:
*
* f.cancel()
* //=> A cancellation attempt was made!
* }}}
*
* =Note on the ExecutionModel=
*
* `Task` is conservative in how it introduces async boundaries.
* Transformations like `map` and `flatMap` for example will default
* to being executed on the current call stack on which the
* asynchronous computation was started. But one shouldn't make
* assumptions about how things will end up executed, as ultimately
* it is the implementation's job to decide on the best execution
* model. All you are guaranteed (and can assume) is asynchronous
* execution after executing `runAsync()`.
*
* Currently the default
* [[monix.execution.ExecutionModel ExecutionModel]] specifies
* batched execution by default and `Task` in its evaluation respects
* the injected `ExecutionModel`. If you want a different behavior,
* you need to execute the `Task` reference with a different scheduler.
*
* @define runAsyncDesc Triggers the asynchronous execution.
*
* Without invoking `runAsync` on a `Task`, nothing
* gets evaluated, as a `Task` has lazy behavior.
*/
sealed abstract class Task[+A] extends Serializable { self =>
import monix.eval.Task._
/** $runAsyncDesc
*
* @param cb is a callback that will be invoked upon completion.
*
* @param s is an injected [[monix.execution.Scheduler Scheduler]]
* that gets used whenever asynchronous boundaries are needed
* when evaluating the task
*
* @return a [[monix.execution.Cancelable Cancelable]] that can
* be used to cancel a running task
*/
def runAsync(cb: Callback[A])(implicit s: Scheduler): Cancelable =
TaskRunLoop.startLightWithCallback(self, s, cb)
/** Similar to Scala's `Future#onComplete`, this method triggers
* the evaluation of a `Task` and invokes the given callback whenever
* the result is available.
*
* @param f is a callback that will be invoked upon completion.
*
* @param s is an injected [[monix.execution.Scheduler Scheduler]]
* that gets used whenever asynchronous boundaries are needed
* when evaluating the task
*
* @return a [[monix.execution.Cancelable Cancelable]] that can
* be used to cancel a running task
*/
def runOnComplete(f: Try[A] => Unit)(implicit s: Scheduler): Cancelable =
runAsync(new Callback[A] {
def onSuccess(value: A): Unit = f(Success(value))
def onError(ex: Throwable): Unit = f(Failure(ex))
})
/** $runAsyncDesc
*
* @param s is an injected [[monix.execution.Scheduler Scheduler]]
* that gets used whenever asynchronous boundaries are needed
* when evaluating the task
*
* @return a [[monix.execution.CancelableFuture CancelableFuture]]
* that can be used to extract the result or to cancel
* a running task.
*/
def runAsync(implicit s: Scheduler): CancelableFuture[A] =
TaskRunLoop.startAsFuture(this, s)
/** Tries to execute the source synchronously.
*
* As an alternative to `runAsync`, this method tries to execute
* the source task immediately on the current thread and call-stack.
*
* This method can throw whatever error is generated by the
* source task, whenever that error is available immediately,
* otherwise errors are signaled asynchronously by means of
* `CancelableFuture`.
*
* @return `Right(result)` in case a result was processed,
* or `Left(future)` in case an asynchronous boundary
* was hit and further async execution is needed
*/
def runSyncMaybe(implicit s: Scheduler): Either[CancelableFuture[A], A] = {
val f = this.runAsync(s)
f.value match {
case None => Left(f)
case Some(Success(a)) => Right(a)
case Some(Failure(ex)) => throw ex
}
}
/** Creates a new [[Task]] that will expose any triggered error
* from the source.
*/
def attempt: Task[Either[Throwable, A]] =
FlatMap(this, AttemptTask.asInstanceOf[Transformation[A, Task[Either[Throwable, A]]]], null)
/** Transforms a [[Task]] into a [[Coeval]] that tries to execute the
* source synchronously, returning either `Right(value)` in case a
* value is available immediately, or `Left(future)` in case we
* have an asynchronous boundary.
*/
def coeval(implicit s: Scheduler): Coeval[Either[CancelableFuture[A], A]] =
Coeval.eval(runSyncMaybe(s))
/** Returns a failed projection of this task.
*
* The failed projection is a `Task` holding a value of type `Throwable`,
* emitting the error yielded by the source, in case the source fails,
* otherwise if the source succeeds the result will fail with a
* `NoSuchElementException`.
*/
def failed: Task[Throwable] =
transformWith(_ => Error(new NoSuchElementException("failed")), e => Now(e))
/** Creates a new Task by applying a function to the successful result
* of the source Task, and returns a task equivalent to the result
* of the function.
*/
def flatMap[B](f: A => Task[B]): Task[B] =
FlatMap(this, f, null)
/** Given a source Task that emits another Task, this function
* flattens the result, returning a Task equivalent to the emitted
* Task by the source.
*/
def flatten[B](implicit ev: A <:< Task[B]): Task[B] =
flatMap(a => a)
/** Returns a task that waits for the specified `timespan` before
* executing and mirroring the result of the source.
*
* @see [[delayExecutionWith]] for delaying the execution of the
* source with a customizable trigger.
*/
def delayExecution(timespan: FiniteDuration): Task[A] =
TaskDelayExecution(self, timespan)
/** Returns a task that waits for the specified `trigger` to succeed
* before mirroring the result of the source.
*
* If the `trigger` ends in error, then the resulting task will
* also end in error.
*
* As an example, these are equivalent (in the observed effects and
* result, not necessarily in implementation):
* {{{
* val ta = source.delayExecution(10.seconds)
* val tb = source.delayExecutionWith(Task.unit.delayExecution(10.seconds))
* }}}
*
* @see [[delayExecution]] for delaying the execution of the
* source with a simple timespan
*/
def delayExecutionWith(trigger: Task[Any]): Task[A] =
TaskDelayExecutionWith(self, trigger)
/** Returns a task that executes the source immediately on `runAsync`,
* but before emitting the `onSuccess` result for the specified
* duration.
*
* Note that if an error happens, then it is streamed immediately
* with no delay.
*
* @see [[delayResultBySelector]] for applying different
* delay strategies depending on the signaled result.
*/
def delayResult(timespan: FiniteDuration): Task[A] =
TaskDelayResult(self, timespan)
/** Returns a task that executes the source immediately on `runAsync`,
* but with the result delayed by the specified `selector`.
*
* The `selector` generates another `Task` whose execution will
* delay the signaling of the result generated by the source.
* Compared with [[delayResult]] this gives you an opportunity
* to apply different delay strategies depending on the
* signaled result.
*
* As an example, these are equivalent (in the observed effects
* and result, not necessarily in implementation):
* {{{
* val t1 = source.delayResult(10.seconds)
* val t2 = source.delayResultBySelector(_ =>
* Task.unit.delayExecution(10.seconds))
* }}}
*
* Note that if an error happens, then it is streamed immediately
* with no delay.
*
* @see [[delayResult]] for delaying with a simple timeout
*/
def delayResultBySelector[B](selector: A => Task[B]): Task[A] =
TaskDelayResultBySelector(self, selector)
/** Overrides the default [[monix.execution.Scheduler Scheduler]],
* possibly forcing an asynchronous boundary before execution
* (if `forceAsync` is set to `true`, the default).
*
* When a `Task` is executed with [[Task.runAsync(implicit* .runAsync]],
* it needs a `Scheduler`, which is going to be injected in all
* asynchronous tasks processed within the `flatMap` chain,
* a `Scheduler` that is used to manage asynchronous boundaries
* and delayed execution.
*
* This scheduler passed in `runAsync` is said to be the "default"
* and `executeOn` overrides that default.
*
* {{{
* import monix.execution.Scheduler
* import java.io.{BufferedReader, FileInputStream, InputStreamReader}
*
* /** Reads the contents of a file using blocking I/O. */
* def readFile(path: String): Task[String] = Task.eval {
* val in = new BufferedReader(
* new InputStreamReader(new FileInputStream(path), "utf-8"))
*
* val buffer = new StringBuffer()
* var line: String = null
* do {
* line = in.readLine()
* if (line != null) buffer.append(line)
* } while (line != null)
*
* buffer.toString
* }
*
* // Building a Scheduler meant for blocking I/O
* val io = Scheduler.io()
*
* // Building the Task reference, specifying that `io` should be
* // injected as the Scheduler for managing async boundaries
* readFile("path/to/file").executeOn(io, forceAsync = true)
* }}}
*
* In this example we are using [[Task.eval]], which executes the
* given `thunk` immediately (on the current thread and call stack).
*
* By calling `executeOn(io)`, we are ensuring that the used
* `Scheduler` (injected in [[Task.unsafeCreate async tasks]] by
* means of [[Task.Context]]) will be `io`, a `Scheduler` that we
* intend to use for blocking I/O actions. And we are also forcing
* an asynchronous boundary right before execution, by passing
* the `forceAsync` parameter as `true` (which happens to be
* the default value).
*
* Thus, for our described function that reads files using Java's
* blocking I/O APIs, we are ensuring that execution is entirely
* managed by an `io` scheduler, executing that logic on a thread
* pool meant for blocking I/O actions.
*
* Note that in case `forceAsync = false`, then the invocation will
* not introduce any async boundaries of its own and will not
* ensure that execution will actually happen on the given
* `Scheduler`, that depending of the implementation of the `Task`.
* For example:
*
* {{{
* Task.eval("Hello, " + "World!")
* .executeOn(io, forceAsync = false)
* }}}
*
* The evaluation of this task will probably happen immediately
* (depending on the configured
* [[monix.execution.ExecutionModel ExecutionModel]]) and the
* given scheduler will probably not be used at all.
*
* However in case we would use [[Task.apply]], which ensures
* that execution of the provided thunk will be async, then
* by using `executeOn` we'll indeed get a logical fork on
* the `io` scheduler:
*
* {{{
* Task("Hello, " + "World!")
* .executeOn(io, forceAsync = false)
* }}}
*
* Also note that overriding the "default" scheduler can only
* happen once, because it's only the "default" that can be
* overridden.
*
* Something like this won't have the desired effect:
*
* {{{
* val io1 = Scheduler.io()
* val io2 = Scheduler.io()
*
* task.executeOn(io1).executeOn(io2)
* }}}
*
* In this example the implementation of `task` will receive
* the reference to `io` and will use it on evaluation, while
* the second invocation of `executeOn` will create an unnecessary
* async boundary (if `forceAsync = true`) or be basically a
* costly no-op. This might be confusing but consider the
* equivalence to these functions:
*
* {{{
* import scala.concurrent.ExecutionContext
*
* val io1 = Scheduler.io()
* val io2 = Scheduler.io()
*
* def sayHello(ec: ExecutionContext): Unit =
* ec.execute(new Runnable {
* def run() = println("Hello!")
* })
*
* def sayHello2(ec: ExecutionContext): Unit =
* // Overriding the default `ec`!
* sayHello(io)
*
* def sayHello3(ec: ExecutionContext): Unit =
* // Overriding the default no longer has the desired effect
* // because sayHello2 is ignoring it!
* sayHello2(io2)
* }}}
*
* @param s is the [[monix.execution.Scheduler Scheduler]] to use
* for overriding the default scheduler and for forcing
* an asynchronous boundary if `forceAsync` is `true`
*
* @param forceAsync indicates whether an asynchronous boundary
* should be forced right before the evaluation of the
* `Task`, managed by the provided `Scheduler`
*
* @return a new `Task` that mirrors the source on evaluation,
* but that uses the provided scheduler for overriding
* the default and possibly force an extra asynchronous
* boundary on execution
*/
def executeOn(s: Scheduler, forceAsync: Boolean = true): Task[A] =
TaskExecuteOn(self, s, forceAsync)
/** Mirrors the given source `Task`, but upon execution ensure
* that evaluation forks into a separate (logical) thread.
*
* The [[monix.execution.Scheduler Scheduler]] used will be
* the one that is used to start the run-loop in
* [[Task.runAsync(implicit* .runAsync]].
*
* This operation is equivalent with:
*
* {{{
* Task.shift.flatMap(_ => task)
*
* // ... or ...
*
* import cats.syntax.all._
*
* Task.shift.followedBy(task)
* }}}
*
* The [[monix.execution.Scheduler Scheduler]] used for scheduling
* the async boundary will be the default, meaning the one used to
* start the run-loop in `runAsync`.
*/
def executeWithFork: Task[A] =
Task.shift.flatMap(_ => self)
/** Returns a new task that will execute the source with a different
* [[monix.execution.ExecutionModel ExecutionModel]].
*
* This allows fine-tuning the options injected by the scheduler
* locally. Example:
*
* {{{
* import monix.execution.ExecutionModel.AlwaysAsyncExecution
* task.executeWithModel(AlwaysAsyncExecution)
* }}}
*
* @param em is the
* [[monix.execution.ExecutionModel ExecutionModel]]
* with which the source will get evaluated on `runAsync`
*/
def executeWithModel(em: ExecutionModel): Task[A] =
TaskExecuteWithModel(self, em)
/** Returns a new task that will execute the source with a different
* set of [[Task.Options Options]].
*
* This allows fine-tuning the default options. Example:
*
* {{{
* task.executeWithOptions(_.enableAutoCancelableRunLoops)
* }}}
*
* @param f is a function that takes the source's current set of
* [[Task.Options options]] and returns a modified set of
* options that will be used to execute the source
* upon `runAsync`
*/
def executeWithOptions(f: Options => Options): Task[A] =
TaskExecuteWithOptions(self, f)
/** Introduces an asynchronous boundary at the current stage in the
* asynchronous processing pipeline.
*
* Consider the following example:
*
* {{{
* import monix.execution.Scheduler
* val io = Scheduler.io()
*
* val source = Task(1).executeOn(io).map(_ + 1)
* }}}
*
* That task is being forced to execute on the `io` scheduler,
* including the `map` transformation that follows after
* `executeOn`. But what if we want to jump with the execution
* run-loop on the default scheduler for the following
* transformations?
*
* Then we can do:
*
* {{{
* source.asyncBoundary.map(_ + 2)
* }}}
*
* In this sample, whatever gets evaluated by the `source` will
* happen on the `io` scheduler, however the `asyncBoundary` call
* will make all subsequent operations to happen on the default
* scheduler.
*/
def asyncBoundary: Task[A] =
self.flatMap(r => Task.shift.map(_ => r))
/** Introduces an asynchronous boundary at the current stage in the
* asynchronous processing pipeline, making processing to jump on
* the given [[monix.execution.Scheduler Scheduler]] (until the
* next async boundary).
*
* Consider the following example:
* {{{
* import monix.execution.Scheduler
* val io = Scheduler.io()
*
* val source = Task(1).executeOn(io).map(_ + 1)
* }}}
*
* That task is being forced to execute on the `io` scheduler,
* including the `map` transformation that follows after
* `executeOn`. But what if we want to jump with the execution
* run-loop on another scheduler for the following transformations?
*
* Then we can do:
* {{{
* import monix.execution.Scheduler.global
*
* source.asyncBoundary(global).map(_ + 2)
* }}}
*
* In this sample, whatever gets evaluated by the `source` will
* happen on the `io` scheduler, however the `asyncBoundary` call
* will make all subsequent operations to happen on the specified
* `global` scheduler.
*
* @param s is the scheduler triggering the asynchronous boundary
*/
def asyncBoundary(s: Scheduler): Task[A] =
self.flatMap(a => Task.shift(s).map(_ => a))
/** Returns a new task that upon evaluation will execute the given
* function for the generated element, transforming the source into
* a `Task[Unit]`.
*
* Similar in spirit with normal [[foreach]], but lazy, as
* obviously nothing gets executed at this point.
*/
def foreachL(f: A => Unit): Task[Unit] =
self.map { a => f(a); () }
/** Triggers the evaluation of the source, executing the given
* function for the generated element.
*
* The application of this function has strict behavior, as the
* task is immediately executed.
*/
def foreach(f: A => Unit)(implicit s: Scheduler): CancelableFuture[Unit] =
foreachL(f).runAsync(s)
/** Returns a new Task that applies the mapping function to the
* element emitted by the source.
*/
def map[B](f: A => B): Task[B] =
flatMap(a => try now(f(a)) catch { case NonFatal(ex) => raiseError(ex) })
/** Returns a new `Task` in which `f` is scheduled to be run on
* completion. This would typically be used to release any
* resources acquired by this `Task`.
*
* The returned `Task` completes when both the source and the task
* returned by `f` complete.
*
* NOTE: The given function is only called when the task is
* complete. However the function does not get called if the task
* gets canceled. Cancellation is a process that's concurrent with
* the execution of a task and hence needs special handling.
*
* See [[doOnCancel]] for specifying a callback to call on
* canceling a task.
*/
def doOnFinish(f: Option[Throwable] => Task[Unit]): Task[A] =
transformWith(
a => f(None).map(_ => a),
e => f(Some(e)).flatMap(_ => Error(e))
)
/** Returns a new `Task` that will mirror the source, but that will
* execute the given `callback` if the task gets canceled before
* completion.
*
* This only works for premature cancellation. See [[doOnFinish]]
* for triggering callbacks when the source finishes.
*
* @param callback is the callback to execute if the task gets
* canceled prematurely
*/
def doOnCancel(callback: Task[Unit]): Task[A] =
TaskDoOnCancel(self, callback)
/** Creates a new [[Task]] that will expose any triggered error from
* the source.
*/
def materialize: Task[Try[A]] =
FlatMap(this, MaterializeTask.asInstanceOf[Transformation[A, Task[Try[A]]]], null)
/** Dematerializes the source's result from a `Try`. */
def dematerialize[B](implicit ev: A <:< Try[B]): Task[B] =
self.asInstanceOf[Task[Try[B]]].flatMap(fromTry)
/** Creates a new task that will try recovering from an error by
* matching it with another task using the given partial function.
*
* See [[onErrorHandleWith]] for the version that takes a total function.
*/
def onErrorRecoverWith[B >: A](pf: PartialFunction[Throwable, Task[B]]): Task[B] =
onErrorHandleWith(ex => pf.applyOrElse(ex, raiseConstructor))
/** Creates a new task that will handle any matching throwable that
* this task might emit by executing another task.
*
* See [[onErrorRecoverWith]] for the version that takes a partial function.
*/
def onErrorHandleWith[B >: A](f: Throwable => Task[B]): Task[B] =
FlatMap(this, null, f)
/** Creates a new task that in case of error will fallback to the
* given backup task.
*/
def onErrorFallbackTo[B >: A](that: Task[B]): Task[B] =
onErrorHandleWith(_ => that)
/** Given a predicate function, keep retrying the
* task until the function returns true.
*/
def restartUntil(p: (A) => Boolean): Task[A] =
self.flatMap(a => if (p(a)) now(a) else self.restartUntil(p))
/** Creates a new task that in case of error will retry executing the
* source again and again, until it succeeds.
*
* In case of continuous failure the total number of executions
* will be `maxRetries + 1`.
*/
def onErrorRestart(maxRetries: Long): Task[A] =
self.onErrorHandleWith(ex =>
if (maxRetries > 0) self.onErrorRestart(maxRetries-1)
else raiseError(ex))
/** Creates a new task that in case of error will retry executing the
* source again and again, until it succeeds.
*
* In case of continuous failure the total number of executions
* will be `maxRetries + 1`.
*/
def onErrorRestartIf(p: Throwable => Boolean): Task[A] =
self.onErrorHandleWith(ex => if (p(ex)) self.onErrorRestartIf(p) else raiseError(ex))
/** Creates a new task that will handle any matching throwable that
* this task might emit.
*
* See [[onErrorRecover]] for the version that takes a partial function.
*/
def onErrorHandle[U >: A](f: Throwable => U): Task[U] =
onErrorHandleWith(f.andThen(nowConstructor))
/** Creates a new task that on error will try to map the error
* to another value using the provided partial function.
*
* See [[onErrorHandle]] for the version that takes a total function.
*/
def onErrorRecover[U >: A](pf: PartialFunction[Throwable, U]): Task[U] =
onErrorRecoverWith(pf.andThen(now))
/** Memoizes (caches) the result of the source task and reuses it on
* subsequent invocations of `runAsync`.
*
* The resulting task will be idempotent, meaning that
* evaluating the resulting task multiple times will have the
* same effect as evaluating it once.
*
* @see [[memoizeOnSuccess]] for a version that only caches
* successful results
*/
def memoize: Task[A] =
self match {
case Now(_) | Error(_) =>
self
case Eval(f) =>
f match {
case _:Coeval.Once[_] => self
case _ =>
val coeval = Coeval.Once(f)
Eval(coeval)
}
case ref: MemoizeSuspend[_] if ref.isCachingAll =>
self
case other =>
new MemoizeSuspend[A](() => other, cacheErrors = true)
}
/** Memoizes (cache) the successful result of the source task
* and reuses it on subsequent invocations of `runAsync`.
* Thrown exceptions are not cached.
*
* The resulting task will be idempotent, but only if the
* result is successful.
*
* @see [[memoize]] for a version that caches both successful
* results and failures
*/
def memoizeOnSuccess: Task[A] =
self match {
case Now(_) | Error(_) =>
self
case Eval(f) =>
val lf = LazyOnSuccess(f)
if (lf eq f) self else Eval(lf)
case _: MemoizeSuspend[_] =>
self
case other =>
new MemoizeSuspend[A](() => other, cacheErrors = false)
}
/** Converts the source `Task` to a `cats.effect.IO` value. */
def toIO(implicit s: Scheduler): IO[A] =
TaskConversions.toIO(this)(s)
/** Converts a [[Task]] to an `org.reactivestreams.Publisher` that
* emits a single item on success, or just the error on failure.
*
* See [[http://www.reactive-streams.org/ reactive-streams.org]] for the
* Reactive Streams specification.
*/
def toReactivePublisher(implicit s: Scheduler): org.reactivestreams.Publisher[A @uV] =
TaskToReactivePublisher[A](self)(s)
/** Returns a Task that mirrors the source Task but that triggers a
* `TimeoutException` in case the given duration passes without the
* task emitting any item.
*/
def timeout(after: FiniteDuration): Task[A] =
timeoutTo(after, raiseError(new TimeoutException(s"Task timed-out after $after of inactivity")))
/** Returns a Task that mirrors the source Task but switches to the
* given backup Task in case the given duration passes without the
* source emitting any item.
*/
def timeoutTo[B >: A](after: FiniteDuration, backup: Task[B]): Task[B] =
Task.chooseFirstOf(self, backup.delayExecution(after)).map {
case Left(((a, futureB))) =>
futureB.cancel()
a
case Right((futureA, b)) =>
futureA.cancel()
b
}
/** Creates a new `Task` by applying the 'fa' function to the successful result of
* this future, or the 'fe' function to the potential errors that might happen.
*
* This function is similar with [[map]], except that it can also transform
* errors and not just successful results.
*
* @param fa function that transforms a successful result of the receiver
* @param fe function that transforms an error of the receiver
*/
def transform[R](fa: A => R, fe: Throwable => R): Task[R] =
transformWith(fa.andThen(nowConstructor), fe.andThen(nowConstructor))
/** Creates a new `Task` by applying the 'fa' function to the successful result of
* this future, or the 'fe' function to the potential errors that might happen.
*
* This function is similar with [[flatMap]], except that it can also transform
* errors and not just successful results.
*
* @param fa function that transforms a successful result of the receiver
* @param fe function that transforms an error of the receiver
*/
def transformWith[R](fa: A => Task[R], fe: Throwable => Task[R]): Task[R] =
FlatMap(this, fa, fe)
/** Zips the values of `this` and `that` task, and creates a new task
* that will emit the tuple of their results.
*/
def zip[B](that: Task[B]): Task[(A, B)] =
Task.mapBoth(this, that)((a,b) => (a,b))
/** Zips the values of `this` and `that` and applies the given
* mapping function on their results.
*/
def zipMap[B,C](that: Task[B])(f: (A,B) => C): Task[C] =
Task.mapBoth(this, that)(f)
}
/** Builders for [[Task]].
*
* @define createAsyncDesc Create a `Task` from an
* asynchronous computation, which takes the form of a
* function with which we can register a callback.
*
* This can be used to translate from a callback-based API to
* a straightforward monadic version.
*
* @define registerParamDesc is a function that will be called when
* this `Task` is executed, receiving a callback as a
* parameter, a callback that the user is supposed to call in
* order to signal the desired outcome of this `Task`.
*
* @define shiftDesc For example we can introduce an
* asynchronous boundary in the `flatMap` chain before a
* certain task, this being literally the implementation of
* [[Task.fork[A](fa:monix\.eval\.Task[A])* Task.fork(fa)]]:
*
* {{{
* Task.shift.flatMap(_ => task)
* }}}
*
* And this can also be described with `followedBy` from Cats:
*
* {{{
* import cats.syntax.all._
*
* Task.shift.followedBy(task)
* }}}
*
* Or we can specify an asynchronous boundary ''after''
* the evaluation of a certain task, this being literally
* the implementation of
* [[Task!.asyncBoundary:monix\.eval\.Task[A]* .asyncBoundary]]:
*
* {{{
* task.flatMap(a => Task.shift.map(_ => a))
* }}}
*