Skip to content

Commit 0ebabc2

Browse files
committed
Implement CompletionStage toCompletableFuture
1 parent e5884cd commit 0ebabc2

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

src/manifold/deferred.clj

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,9 @@
6969
then-compose then-compose-async
7070

7171
then-handle then-handle-async
72-
then-exceptionally)
72+
then-exceptionally
73+
74+
to-completable-future)
7375

7476
;; The potemkin abstract type for
7577
;; implementations such as CompletionStage
@@ -153,7 +155,10 @@
153155
(then-handle-async this operator executor))
154156

155157
(exceptionally [this operator]
156-
(then-exceptionally this operator)))
158+
(then-exceptionally this operator))
159+
160+
(toCompletableFuture [this]
161+
(to-completable-future this)))
157162

158163
(definline realized?
159164
"Returns true if the manifold deferred is realized."
@@ -1625,6 +1630,17 @@
16251630
(assert-some operator)
16261631
(catch this #(.apply operator %)))
16271632

1633+
(defn- to-completable-future [this]
1634+
1635+
(let [result (java.util.concurrent.CompletableFuture.)]
1636+
1637+
(on-realized this
1638+
#(.complete result %)
1639+
#(.completeExceptionally result %))
1640+
1641+
result
1642+
))
1643+
16281644
;;;
16291645

16301646
(alter-meta! #'->Deferred assoc :private true)

test/manifold/deferred_stage_test.clj

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -454,3 +454,28 @@
454454

455455
(is (thrown? RuntimeException @d1))
456456
(is (= 2 @d2)))))
457+
458+
(deftest test-to-completable-future
459+
(testing ".toCompletableFuture success"
460+
(let [base ^CompletionStage (d/deferred)
461+
target ^CompletableFuture (.toCompletableFuture base)]
462+
463+
(is (not (.isDone target)))
464+
465+
(d/success! base 10)
466+
467+
(is (.isDone target))
468+
469+
(is (= 10 (.get target)))))
470+
471+
(testing ".toCompletableFuture error"
472+
(let [base ^CompletionStage (d/deferred)
473+
target ^CompletableFuture (.toCompletableFuture base)]
474+
475+
(is (not (.isDone target)))
476+
477+
(d/error! base (RuntimeException.))
478+
479+
(is (.isDone target))
480+
481+
(is (thrown? RuntimeException (.getNow target nil))))))

0 commit comments

Comments
 (0)