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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
|
<chapter id="Reactive">
<title>Reactive programming support</title>
<para>
With version 2.1, the JAX-RS specification
(<ulink url="https://jcp.org/en/jsr/detail?id=370">https://jcp.org/en/jsr/detail?id=370</ulink>)
takes its first steps into the world of <emphasis role="bold">Reactive Programming</emphasis>. There are many discussions
of reactive programming on the internet, and a general introduction is beyond the scope of this document,
but there are a few things worth discussing. Some primary aspects of reactive programming are the following:
</para>
<itemizedlist>
<listitem>
Reactive programming supports the declarative creation of rich computational structures. The
representations of these structures can be passed around as first class objects such as method parameters
and return values.
</listitem>
<listitem>
Reactive programming supports both synchronous and asynchronous computation, but it is particularly helpful
in facilitating, at a relatively high level of expression, asynchronous computation. Conceptually,
asynchronous computation in reactive program typically involves pushing data from one entity to another, rather
than polling for data.
</listitem>
</itemizedlist>
<sect1>
<title>CompletionStage</title>
<para>
In java 1.8 and JAX-RS 2.1, the support for reactive programming is fairly limited. Java 1.8 introduces the interface
<classname>java.util.concurrent.CompletionStage</classname>, and JAX-RS 2.1 mandates support for the
<classname>javax.ws.rs.client.CompletionStageRxInvoker</classname>, which allows a client to obtain a
response in the form of a <classname>CompletionStage</classname>.
</para>
<para>
One implementation of <classname>CompletionStage</classname> is the <classname>java.util.concurrent.CompleteableFuture</classname>.
For example:
</para>
<programlisting>
@Test
public void testCompletionStage() throws Exception {
CompletionStage<String> stage = getCompletionStage();
log.info("result: " + stage.toCompletableFuture().get());
}
private CompletionStage<String> getCompletionStage() {
CompletableFuture<String> future = new CompletableFuture<String>();
future.complete("foo");
return future;
}
</programlisting>
<para>
Here, a <classname>CompleteableFuture</classname> is created with the value "foo", and its value is
extracted by the method <methodname>CompletableFuture.get()</methodname>. That's fine, but consider the
altered version:
</para>
<programlisting>
@Test
public void testCompletionStageAsync() throws Exception {
log.info("start");
CompletionStage<String> stage = getCompletionStageAsync();
String result = stage.toCompletableFuture().get();
log.info("do some work");
log.info("result: " + result);
}
private CompletionStage<String> getCompletionStageAsync() {
CompletableFuture<String> future = new CompletableFuture<String>();
Executors.newCachedThreadPool().submit(() -> {sleep(2000); future.complete("foo");});
return future;
}
private void sleep(long l) {
try {
Thread.sleep(l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
</programlisting>
<para>
with output something like:
</para>
<programlisting>
3:10:51 PM INFO: start
3:10:53 PM INFO: do some work
3:10:53 PM INFO: result: foo
</programlisting>
<para>
It also works, but it illustrates the fact that <methodname>CompletableFuture.get()</methodname> is a blocking
call. The <classname>CompletionStage</classname> is constructed and returned immediately,
but the value isn't returned for two seconds. A version that is more in the spirit of the reactive style is:
</para>
<programlisting>
@Test
public void testCompletionStageAsyncAccept() throws Exception {
log.info("start");
CompletionStage<String> stage = getCompletionStageAsync();
stage.thenAccept((String s) -> log.info("s: " + s));
log.info("do some work");
...
}
</programlisting>
<para>
In this case, the lambda (String s) -> log.info("s: " + s) is registered with the
<classname>CompletionStage</classname> as a "subscriber", and, when the <classname>CompletionStage</classname>
eventually has a value, that value is passed to the lambda. Note that the output is something like
</para>
<programlisting>
3:23:05 INFO: start
3:23:05 INFO: do some work
3:23:07 INFO: s: foo
</programlisting>
<para>
Executing <classname>CompletionStage</classname>s asynchronously is so common that there are
several supporting convenience methods. For example:
</para>
<programlisting>
@Test
public void testCompletionStageSupplyAsync() throws Exception {
CompletionStage<String> stage = getCompletionStageSupplyAsync();;
stage.thenAccept((String s) -> log.info("s: " + s));
}
private CompletionStage<String> getCompletionStageSupplyAsync() {
return CompletableFuture.supplyAsync(() -> "foo");
}
</programlisting>
<para>
The static method <classname>ComputableFuture.supplyAsync()</classname> creates a
<classname>ComputableFuture</classname>, the value of which is supplied asynchronously
by the lambda () -> "foo", running, by default, in the default pool of
<methodname>java.util.concurrent.ForkJoinPool</methodname>.
</para>
<para>
One final example illustrates a more complex computational structure:
</para>
<programlisting>
@Test
public void testCompletionStageComplex() throws Exception {
ExecutorService executor = Executors.newCachedThreadPool();
CompletionStage<String> stage1 = getCompletionStageSupplyAsync1("foo", executor);
CompletionStage<String> stage2 = getCompletionStageSupplyAsync1("bar", executor);
CompletionStage<String> stage3 = stage1.thenCombineAsync(stage2, (String s, String t) -> s + t, executor);
stage3.thenAccept((String s) -> log.info("s: " + s));
}
private CompletionStage<String> getCompletionStageSupplyAsync1(String s, ExecutorService executor) {
return CompletableFuture.supplyAsync(() -> s, executor);
}
</programlisting>
<para>
<classname>stage1</classname> returns "foo", <classname>stage2</classname> returns "bar", and
<classname>stage3</classname>, which runs when both <classname>stage1</classname> and <classname>stage2</classname>
have completed, returns the concatenation of "foo" and "bar". Note that, in this example, an explict
<classname>ExecutorService</classname> is provided for asynchronous processing.
</para>
</sect1>
<sect1>
<title>CompletionStage in JAX-RS</title>
<para>
On the client side, the JAX-RS 2.1 specification mandates an implementation of the interface
<classname>javax.ws.rs.client.CompletionStageRxInvoker</classname>:
</para>
<programlisting>
public interface CompletionStageRxInvoker extends RxInvoker<CompletionStage> {
@Override
public CompletionStage<Response> get();
@Override
public <T> CompletionStage<T> get(Class<T> responseType);
@Override
public <T> CompletionStage<T> get(GenericType<T> responseType);
...
</programlisting>
<para>
That is, there are invocation methods for the standard HTTP verbs, just as in the standard
<classname>javax.ws.rs.client.SyncInvoker</classname>. A <classname>CompletionStageRxInvoker</classname>
is obtained by calling <methodname>rx()</methodname> on a
<classname>javax.ws.rs.client.Invocation.Builder</classname>, which extends <classname>SyncInvoker</classname>.
For example,
</para>
<programlisting>
Invocation.Builder builder = client.target(generateURL("/get/string")).request();
CompletionStageRxInvoker invoker = builder.rx(CompletionStageRxInvoker.class);
CompletionStage<Response> stage = invoker.get();
Response response = stage.toCompletableFuture().get();
log.info("result: " + response.readEntity(String.class));
</programlisting>
<para>
or
</para>
<programlisting>
CompletionStageRxInvoker invoker = client.target(generateURL("/get/string")).request().rx(CompletionStageRxInvoker.class);
CompletionStage<String> stage = invoker.get(String.class);
String s = stage.toCompletableFuture().get();
log.info("result: " + s);
</programlisting>
<para>
On the server side, the JAX-RS 2.1 specification requires support for resource methods with return type
<classname>CompletionStage<T></classname>. For example,
</para>
<programlisting>
@GET
@Path("get/async")
public CompletionStage<String> longRunningOpAsync() {
CompletableFuture<String> cs = new CompletableFuture<>();
executor.submit(
new Runnable() {
public void run() {
executeLongRunningOp();
cs.complete("Hello async world!");
}
});
return cs;
}
</programlisting>
<para>
The way to think about <methodname>longRunningOpAsync()</methodname> is that it is asynchronously
creating and returning a <classname>String</classname>. After <classname>cs.complete()</classname> is called,
the server will return the <classname>String</classname> "Hello async world!" to the client.
</para>
<para>
An important thing to understand is that the decision to produce a result asynchronously on the server and the
decision to retrieve the result asynchronously on the client are independent. Suppose that there is also a
resource method
</para>
<programlisting>
@GET
@Path("get/sync")
public String longRunningOpSync() {
return "Hello async world!";
}
</programlisting>
<para>
Then all three of the following invocations are valid:
</para>
<programlisting>
public void testGetStringAsyncAsync() throws Exception {
CompletionStageRxInvoker invoker = client.target(generateURL("/get/async")).request().rx();
CompletionStage<String> stage = invoker.get(String.class);
log.info("s: " + stage.toCompletableFuture().get());
}
</programlisting>
<programlisting>
public void testGetStringSyncAsync() throws Exception {
Builder request = client.target(generateURL("/get/async")).request();
String s = request.get(String.class);
log.info("s: " + s);
}
</programlisting>
<para>
and
</para>
<programlisting>
public void testGetStringAsyncSync() throws Exception {
CompletionStageRxInvoker invoker = client.target(generateURL("/get/sync")).request().rx();
CompletionStage<String> stage = invoker.get(String.class);
log.info("s: " + stage.toCompletableFuture().get());
}
</programlisting>
<note>
<para>
<classname>CompletionStage</classname> in JAX-RS is also discussed in the chapter
<link linkend="Asynchronous_HTTP_Request_Processing">Asynchronous HTTP Request Processing</link>.
</para>
</note>
<note id="asyncContextNote">
<para>
Since running code asynchronously is so common in this context, it is worth pointing out
that objects obtained by way of the annotation <code>@Context</code> or by way of calling
<code>ResteasyProviderFactory.getContextData()</code> are sensitive to the
executing thread. For example, given resource method
</para>
<programlisting>
@GET
@Path("test")
@Produces("text/plain")
public CompletionStage<String> text(@Context HttpRequest request) {
System.out.println("request (inline): " + request);
System.out.println("application (inline): " + ResteasyProviderFactory.getContextData(Application.class));
CompletableFuture<String> cs = new CompletableFuture<>();
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(
new Runnable() {
public void run() {
try {
System.out.println("request (async): " + request);
System.out.println("application (async): " + ResteasyProviderFactory.getContextData(Application.class));
cs.complete("hello");
} catch (Exception e) {
e.printStackTrace();
}
}
});
return cs;
}
</programlisting>
<para>
the output will look something like
</para>
<programlisting>
application (inline): org.jboss.resteasy.experiment.Test1798CompletionStage$TestApp@23c57474
request (inline): org.jboss.resteasy.plugins.server.servlet.Servlet3AsyncHttpRequest@2ce23138
application (async): null
org.jboss.resteasy.spi.LoggableFailure: RESTEASY003880: Unable to find contextual data of type: org.jboss.resteasy.spi.HttpRequest
</programlisting>
<para>
The point is that it is the developer's responsibility to extract information from these context objects
in advance. For example:
</para>
<programlisting>
@GET
@Path("test")
@Produces("text/plain")
public CompletionStage<String> text(@Context HttpRequest req) {
System.out.println("request (inline): " + request);
System.out.println("application (inline): " + ResteasyProviderFactory.getContextData(Application.class));
CompletableFuture<String> cs = new CompletableFuture<>();
ExecutorService executor = Executors.newSingleThreadExecutor();
final String httpMethodFinal = request.getHttpMethod();
final Map<String, Object> mapFinal = ResteasyProviderFactory.getContextData(Application.class).getProperties();
executor.submit(
new Runnable() {
public void run() {
System.out.println("httpMethod (async): " + httpMethodFinal);
System.out.println("map (async): " + mapFinal);
cs.complete("hello");
}
});
return cs;
}
</programlisting>
</note>
</sect1>
<sect1>
<title>Beyond CompletionStage</title>
<para>
The picture becomes more complex and interesting when sequences are added. A <classname>CompletionStage</classname>
holds no more than one potential value, but other reactive objects can hold multiple, even unlimited, values.
Currently, most Java implementations of reactive programming are based on the project Reactive Streams
(<ulink url="http://www.reactive-streams.org/">http://www.reactive-streams.org/</ulink>), which defines a set of
four interfaces and a specification, in the form of a set of rules, describing how they interact:
</para>
<programlisting>
public interface Publisher<T> {
public void subscribe(Subscriber<? super T> s);
}
public interface Subscriber<T> {
public void onSubscribe(Subscription s);
public void onNext(T t);
public void onError(Throwable t);
public void onComplete();
}
public interface Subscription {
public void request(long n);
public void cancel();
}
public interface Processor<T, R> extends Subscriber<T>, Publisher<R> {
}
</programlisting>
<para>
A <classname>Producer</classname> pushes objects to a <classname>Subscriber</classname>, a
<classname>Subscription</classname> mediates the relationship between the two, and a
<classname>Processor</classname> which is derived from both, helps to construct pipelines
through which objects pass.
</para>
<para>
One important aspect of the specification is flow control, the ability of a <classname>Suscriber</classname>
to control the load it receives from a <classname>Producer</classname> by calling
<methodname>Suscription.request()</methodname>. The general term in this context for flow control is
<emphasis role="bold">backpressure</emphasis>.
</para>
<para>
There are a number of implementations of Reactive Streams, including
</para>
<orderedlist>
<listitem><emphasis role="bold">RxJava</emphasis>:
<ulink url="https://github.com/ReactiveX/RxJava">https://github.com/ReactiveX/RxJava</ulink> (end of life, superceded by RxJava 2)
</listitem>
<listitem><emphasis role="bold">RxJava 2</emphasis>:
<ulink url="https://github.com/ReactiveX/RxJava">https://github.com/ReactiveX/RxJava</ulink>
</listitem>
<listitem><emphasis role="bold">Reactor</emphasis>:
<ulink url="http://projectreactor.io/">http://projectreactor.io/</ulink>
</listitem>
<listitem><emphasis role="bold">Flow</emphasis>:
<ulink url="https://community.oracle.com/docs/DOC-1006738">https://community.oracle.com/docs/DOC-1006738/</ulink>:
(Java JDK 9+)
</listitem>
</orderedlist>
<para>
RESTEasy currently supports RxJava (deprecated) and RxJava2.
</para>
</sect1>
<sect1>
<title>Pluggable reactive types: RxJava 2 in RESTEasy</title>
<para>
JAX-RS 2.1 doesn't require support for any Reactive Streams implementations, but it does allow
for extensibility to support various reactive libraries.
RESTEasy's optional modules <code>resteasy-rxjava1</code> and <code>resteasy-rxjava2</code>
add support for <ulink url="https://github.com/ReactiveX/RxJava">RxJava 1 and 2</ulink>.
[Only <code>resteasy-rxjava2</code> will be discussed here, since <code>resteasy-rxjava1</code> is
deprecated, but the treatment of the two is quite similar.]
</para>
<para>
In particular, <code>resteasy-rxjava2</code>
contributes support for reactive types <classname>io.reactivex.Single</classname>,
<classname>io.reactivex.Flowable</classname>, and <classname>io.reactivex.Observable</classname>.
Of these, <classname>Single</classname> is similar to <classname>CompletionStage</classname> in that
it holds at most one potential value. <classname>Flowable</classname> implements
<classname>io.reactivex.Publisher</classname>, and <classname>Observable</classname> is very
similar to <classname>Flowable</classname> except that it doesn't support backpressure.
So, if you import <code>resteasy-rxjava2</code>, you can just start returning these reactive types from your
resource methods on the server side and receiving them on the client side.
</para>
<sect1>
<title>Server side</title>
<para>
Given the class <classname>Thing</classname>, which can be represented in JSON:
</para>
<programlisting>
public class Thing {
private String name;
public Thing() {
}
public Thing(String name) {
this.name = name;
}
...
}
</programlisting>
<para>the method <methodname>postThingList()</methodname> in the following is a valid resource method:
</para>
...
<programlisting>
@POST
@Path("post/thing/list")
@Produces(MediaType.APPLICATION_JSON)
@Stream
public Flowable<List<Thing>> postThingList(String s) {
return buildFlowableThingList(s, 2, 3);
}
static Flowable<List<Thing>> buildFlowableThingList(String s, int listSize, int elementSize) {
return Flowable.create(
new FlowableOnSubscribe<List<Thing>>() {
@Override
public void subscribe(FlowableEmitter<List<Thing>> emitter) throws Exception {
for (int i = 0; i < listSize; i++) {
List<Thing> list = new ArrayList<Thing>();
for (int j = 0; j < elementSize; j++) {
list.add(new Thing(s));
}
emitter.onNext(list);
}
emitter.onComplete();
}
},
BackpressureStrategy.BUFFER);
}
</programlisting>
<para>
The somewhat imposing method <methodname>buildFlowableThingList()</methodname> probably deserves
some explanation. First,
</para>
<programlisting>
Flowable<List<Thing>> Flowable.create(FlowableOnSubscribe<List<Thing>> source, BackpressureStrategy mode);
</programlisting>
<para>
creates a <classname>Flowable<List<Thing>></classname> by describing what should happen when
the <classname>Flowable<List<Thing>></classname> is subscribed to.
<classname>FlowableEmitter<List<Thing>></classname>
extends <classname> io.reactivex.Emitter<List<Thing>></classname>:
</para>
<programlisting>
/**
* Base interface for emitting signals in a push-fashion in various generator-like source
* operators (create, generate).
*
* @param <T> the value type emitted
*/
public interface Emitter<T> {
/**
* Signal a normal value.
* @param value the value to signal, not null
*/
void onNext(@NonNull T value);
/**
* Signal a Throwable exception.
* @param error the Throwable to signal, not null
*/
void onError(@NonNull Throwable error);
/**
* Signal a completion.
*/
void onComplete();
}
</programlisting>
<para>
and <classname>FlowableOnSubscribe</classname> uses a <classname>FlowableEmitter</classname>
to send out values from the <classname>Flowable<List<Thing>></classname>:
</para>
<programlisting>
/**
* A functional interface that has a {@code subscribe()} method that receives
* an instance of a {@link FlowableEmitter} instance that allows pushing
* events in a backpressure-safe and cancellation-safe manner.
*
* @param <T> the value type pushed
*/
public interface FlowableOnSubscribe<T> {
/**
* Called for each Subscriber that subscribes.
* @param e the safe emitter instance, never null
* @throws Exception on error
*/
void subscribe(@NonNull FlowableEmitter<T> e) throws Exception;
}
</programlisting>
<para>
So, what will happen
when a subscription to the <classname>Flowable<List<Thing>></classname> is created is,
the <methodname>FlowableEmitter.onNext()</methodname> will be called, once for each
<classname><List<Thing>></classname> created, followed by a call to
<methodname>FlowableEmitter.onComplete()</methodname> to indicate that the sequence has ended. Under the covers,
RESTEasy subscribes to the <classname>Flowable<List<Thing>></classname> and handles each element passed in
by way of <methodname>onNext()</methodname>.
</para>
</sect1>
<sect1>
<title>Client side</title>
<para>
On the client side, JAX-RS 2.1 supports extensions for reactive classes by adding the method
</para>
<programlisting>
/**
* Access a reactive invoker based on a {@link RxInvoker} subclass provider. Note
* that corresponding {@link RxInvokerProvider} must be registered in the client runtime.
*
* This method is an extension point for JAX-RS implementations to support other types
* representing asynchronous computations.
*
* @param clazz {@link RxInvoker} subclass.
* @return reactive invoker instance.
* @throws IllegalStateException when provider for given class is not registered.
* @see javax.ws.rs.client.Client#register(Class)
* @since 2.1
*/
public <T extends RxInvoker> T rx(Class<T> clazz);
</programlisting>
<para>
to interface <classname> javax.ws.rs.client.Invocation.Builder</classname>. Resteasy
module <code>resteasy-rxjava2</code> adds support for classes:
</para>
<orderedlist>
<listitem><classname>org.jboss.resteasy.rxjava2.SingleRxInvoker</classname>,</listitem>
<listitem><classname>org.jboss.resteasy.rxjava2.FlowableRxInvoker</classname></listitem>, and
<listitem><classname>org.jbosss.resteasy.rxjava2.ObservableRxInvoker</classname></listitem>.
</orderedlist>
<para>
which allow accessing <classname>Single</classname>s, <classname>Observable</classname>s, and
<classname>Flowable</classname>s on the client side.
</para>
<para>
For example, given the resource method <methodname>postThingList()</methodname> above, a
<classname>Flowable<List<Thing>></classname> can be retrieved from the server
by calling
</para>
<programlisting>
@SuppressWarnings("unchecked")
@Test
public void testPostThingList() throws Exception {
CountDownLatch latch = new CountdownLatch(1);
FlowableRxInvoker invoker = client.target(generateURL("/post/thing/list")).request().rx(FlowableRxInvoker.class);
Flowable<List<Thing>> flowable = (Flowable<List<Thing>>) invoker.post(Entity.entity("a", MediaType.TEXT_PLAIN_TYPE), new GenericType<List<Thing>>() {});
flowable.subscribe(
(List<?> l) -> thingListList.add(l),
(Throwable t) -> latch.countDown(),
() -> latch.countDown());
latch.await();
Assert.assertEquals(aThingListList, thingListList);
}
</programlisting>
<para>
where <code>aThingListList</code> is
</para>
<programlisting>
[[Thing[a], Thing[a], Thing[a]], [Thing[a], Thing[a], Thing[a]]]
</programlisting>
<para>
Note the call to <methodname>Flowable.suscribe()</methodname>. On the server side, RESTEasy subscribes to a
returning <classname>Flowable</classname> in order to receive its elements and send them over the wire. On the client side,
the user subscribes to the <classname>Flowable</classname> in order to receive its elements and do whatever it wants to
with them. In this case, three lambdas determine what should happen 1) for each element, 2) if a <classname>Throwable</classname>
is thrown, and 3) when the <classname>Flowable</classname> is done passing elements.
</para>
</sect1>
<sect1>
<title>Representation on the wire</title>
<para>
Neither Reactive Streams nor JAX-RS have anything to say about representing reactive types on the network.
RESTEasy offers a number of representations, each suitable for different circumstances. The wire protocol
is determined by 1) the presence or absence of the <code>@Stream</code> annotation on the resource method,
and 2) the value of the <code>value</code> field in the <code>@Stream</code> annotation:
</para>
<programlisting>
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Stream
{
public enum MODE {RAW, GENERAL};
public String INCLUDE_STREAMING_PARAMETER = "streaming";
public MODE value() default MODE.GENERAL;
public boolean includeStreaming() default false;
}
</programlisting>
<para>
Note that <code>MODE.GENERAL</code> is the default value, so <code>@Stream</code> is equivalent
to <code>@Stream(Stream.MODE.GENERAL)</code>.
</para>
<variablelist>
<varlistentry>
<term>No <code>@Stream</code> annotation on the resource method</term>
<listitem>
Resteasy will collect every value until the stream is complete, then wrap them into a
<code>java.util.List</code> entity and send to the client.
</listitem>
</varlistentry>
<varlistentry>
<term><code>@Stream(Stream.MODE.GENERAL)</code></term>
<listitem>
This case uses a variant of the SSE format, modified to eliminate some restrictions inherent in SSE.
(See the specification at
<ulink url="https://html.spec.whatwg.org/multipage/server-sent-events.html">
https://html.spec.whatwg.org/multipage/server-sent-events.html</ulink> for details.)
In particular, 1) SSE events are meant to hold text data, represented in character set UTF-8. In the general streaming mode,
certain delimiting characters in the data ('\r', '\n', and '\') are escaped so that arbitrary binary data can be
transmitted. Also, 2) the SSE specification requires the client to reconnect if it gets disconnected. If the stream
is finite, reconnecting will induce a repeat of the stream, so SSE is really meant for unlimited streams.
In general streaming mode, the client will close, rather than automatically reconnect, at the end of the stream. It follows
that this mode is suitable for finite streams.
<para>
<emphasis role="bold">Note. </emphasis> The Content-Type header in general streaming mode is set to
</para>
<programlisting>
applicaton/x-stream-general;"element-type=<element-type>"
</programlisting>
<para>
where <element-type>
is the media type of the data elements in the stream. The element media type is derived
from the @Produces annotation. For example,
</para>
<programlisting>
@GET
@Path("flowable/thing")
@Stream
@Produces("application/json")
public Flowable<Thing> getFlowable() { ... }
</programlisting>
<para>
induces the media type
</para>
<programlisting>
application/x-stream-general;"element-type=application/json"
</programlisting>
<para>
which describes a stream of JSON elements.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><code>@Stream(Stream.MODE.RAW)</code></term>
<listitem>
In this case each value is written directly to the wire, without any formatting, as it becomes available.
This is most useful for values that can be cut in pieces, such as strings, bytes, buffers, etc., and then
re-concatenated on the client side. Note that without delimiters as in
general mode, it isn't possible to reconstruct something like <classname>List<List<String>></classname>.
<para>
<emphasis role="bold">Note. </emphasis> The Content-Type header in raw streaming mode is derived from
the <code>@Produces</code> annotation. The <code>@Stream</code> annotation offers the possibility of an
optional <classname>MediaType</classname> parameter called "streaming". The point is to be able to suggest
that the stream of data emanating from the server is unbounded, i.e., that the client shouldn't try to
read it all as a single byte array, for example. The parameter is set by explicitly setting the
<code>@Stream</code> parameter <code>includeStreaming()</code> to <code>true</code>. For example,
</para>
<programlisting>
@GET
@Path("byte/default")
@Produces("application/octet-stream;x=y")
@Stream(Stream.MODE.RAW)
public Flowable<Byte> aByteDefault() {
return Flowable.fromArray((byte) 0, (byte) 1, (byte) 2);
}
</programlisting>
<para>
induces the <classname>MediaType</classname> "application/octet-stream;x=y", and
</para>
<programlisting>
@GET
@Path("byte/true")
@Produces("application/octet-stream;x=y")
@Stream(value=Stream.MODE.RAW, includeStreaming=true)
public Flowable<Byte> aByteTrue() {
return Flowable.fromArray((byte) 0, (byte) 1, (byte) 2);
}
</programlisting>
<para>
induces the <classname>MediaType</classname> "application/octet-stream;x=y;streaming=true".
</para>
<para>
Note that browsers such as Firefox and Chrome seem to be comfortable with reading unlimited streams
without any additional hints.
</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1>
<title>Examples.</title>
<para>
<emphasis role="bold">Example 1.</emphasis>
</para>
<programlisting>
@POST
@Path("post/thing/list")
@Produces(MediaType.APPLICATION_JSON)
@Stream(Stream.MODE.GENERAL)
public Flowable<List<Thing>> postThingList(String s) {
return buildFlowableThingList(s, 2, 3);
}
...
@SuppressWarnings("unchecked")
@Test
public void testPostThingList() throws Exception {
CountDownLatch latch = new CountdownLatch(1);
FlowableRxInvoker invoker = client.target(generateURL("/post/thing/list")).request().rx(FlowableRxInvoker.class);
Flowable<List<Thing>> flowable = (Flowable<List<Thing>>) invoker.post(Entity.entity("a", MediaType.TEXT_PLAIN_TYPE), new GenericType<List<Thing>>() {});
flowable.subscribe(
(List<?> l) -> thingListList.add(l),
(Throwable t) -> latch.countDown(),
() -> latch.countDown());
latch.await();
Assert.assertEquals(aThingListList, thingListList);
}
</programlisting>
<para>
This is the example given previously, except that the mode in the <code>@Stream</code> annotation (which defaults
to MODE.GENERAL) is given explicitly. In this scenario, the <classname>Flowable</classname> emits
<classname><List<Thing>></classname> elements on the server, they are transmitted over the wire as
SSE events:
</para>
<programlisting>
data: [{"name":"a"},{"name":"a"},{"name":"a"}]
data: [{"name":"a"},{"name":"a"},{"name":"a"}]
</programlisting>
<para>
and the <classname>FlowableRxInvoker</classname> reconstitutes a <classname>Flowable</classname> on the
client side.
</para>
<para><emphasis role="bold">Example 2.</emphasis></para>
<programlisting>
@POST
@Path("post/thing/list")
@Produces(MediaType.APPLICATION_JSON)
public Flowable<List<Thing>> postThingList(String s) {
return buildFlowableThingList(s, 2, 3);
}
...
@Test
public void testPostThingList() throws Exception {
Builder request = client.target(generateURL("/post/thing/list")).request();
List<List<Thing>> list = request.post(Entity.entity("a", MediaType.TEXT_PLAIN_TYPE), new GenericType<List<List<Thing>>>() {});
Assert.assertEquals(aThingListList, list);
}
</programlisting>
<para>
In this scenario, in which the resource method has no <code>@Stream</code> annotation, the
<classname>Flowable</classname> emits stream elements which are accumulated by the server until
the <classname>Flowable</classname> is done, at which point the entire JSON list is transmitted over the wire:
</para>
<programlisting>
[[{"name":"a"},{"name":"a"},{"name":"a"}],[{"name":"a"},{"name":"a"},{"name":"a"}]]
</programlisting>
<para>
and the list is reconstituted on the client side by an ordinary invoker.
</para>
<para><emphasis role="bold">Example 3.</emphasis></para>
<programlisting>
@GET
@Path("get/bytes")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Stream(Stream.MODE.RAW)
public Flowable<byte[]> getBytes() {
return Flowable.create(
new FlowableOnSubscribe<byte[]>() {
@Override
public void subscribe(FlowableEmitter<byte[]> emitter) throws Exception {
for (int i = 0; i < 3; i++) {
byte[] b = new byte[10];
for (int j = 0; j < 10; j++) {
b[j] = (byte) (i + j);
}
emitter.onNext(b);
}
emitter.onComplete();
}
},
BackpressureStrategy.BUFFER);
}
...
@Test
public void testGetBytes() throws Exception {
Builder request = client.target(generateURL("/get/bytes")).request();
InputStream is = request.get(InputStream.class);
int n = is.read();
while (n > -1) {
System.out.print(n);
n = is.read();
}
}
</programlisting>
<para>
Here, the byte arrays are written to the network as they are created by the <classname>Flowable</classname>.
On the network, they are concatenated, so the client sees one stream of bytes.
</para>
<note>
<para>
Given that asynchronous code is common in this context, it is worth looking at the earlier
<link linkend="asyncContextNote">Note</link>.
</para>
</note>
</sect1>
<sect1>
<title>Rx and SSE</title>
<para>
Since general streaming mode and SSE share minor variants of the same wire protocol, they are, modulo the SSE
restriction to character data, interchangeable. That is, an SSE client can connect to a resource method that returns
a <classname>Flowable</classname> or an <classname>Observable</classname>, and a <classname>FlowableRxInvoker</classname>,
for example, can connect to an SSE resource method.
</para>
<para>
<emphasis role="bold">Note.</emphasis> SSE requires a <code>@Produces("text/event-stream")</code>
annotation, so, unlike the cases of raw and general streaming, the element media type cannot
be derived from the <code>@Produces</code> annotation. To solve this problem, Resteasy introduces the
</para>
<programlisting>
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SseElementType
{
public String value();
}
</programlisting>
<para>
annotation, from which the element media type is derived.
</para>
<para><emphasis role="bold">Example 1.</emphasis></para>
<programlisting>
@GET
@Path("eventStream/thing")
@Produces("text/event-stream")
@SseElementType("application/json")
public void eventStreamThing(@Context SseEventSink eventSink, @Context Sse sse) {
new ScheduledThreadPoolExecutor(5).execute(() -> {
try (SseEventSink sink = eventSink) {
OutboundSseEvent.Builder builder = sse.newEventBuilder();
eventSink.send(builder.data(new Thing("e1")).build());
eventSink.send(builder.data(new Thing("e2")).build());
eventSink.send(builder.data(new Thing("e3")).build());
}
});
}
...
@SuppressWarnings("unchecked")
@Test
public void testFlowableToSse() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
final AtomicInteger errors = new AtomicInteger(0);
FlowableRxInvoker invoker = client.target(generateURL("/eventStream/thing")).request().rx(FlowableRxInvoker.class);
Flowable<Thing> flowable = (Flowable<Thing>) invoker.get(Thing.class);
flowable.subscribe(
(Thing t) -> thingList.add(t),
(Throwable t) -> errors.incrementAndGet(),
() -> latch.countDown());
boolean waitResult = latch.await(30, TimeUnit.SECONDS);
Assert.assertTrue("Waiting for event to be delivered has timed out.", waitResult);
Assert.assertEquals(0, errors.get());
Assert.assertEquals(eThingList, thingList);
}
</programlisting>
<para>
Here, a <classname>FlowableRxInvoker</classname> is connecting to an SSE resource method. On the network,
the data looks like
</para>
<programlisting>
data: {"name":"e1"}
data: {"name":"e2"}
data: {"name":"e3"}
</programlisting>
<para>
Note that the character data is suitable for an SSE resource method.
</para>
<para>
Also, note that the <methodname>eventStreamThing()</methodname> method in this example induces the media type
</para>
<programlisting>
text/event-stream;element-type="application/json"
</programlisting>
<para><emphasis role="bold">Example 2.</emphasis></para>
<programlisting>
@GET
@Path("flowable/thing")
@Produces("text/event-stream")
@SseElementType("application/json")
public Flowable<Thing> flowableSSE() {
return Flowable.create(
new FlowableOnSubscribe<Thing>() {
@Override
public void subscribe(FlowableEmitter<Thing> emitter) throws Exception {
emitter.onNext(new Thing("e1"));
emitter.onNext(new Thing("e2"));
emitter.onNext(new Thing("e3"));
emitter.onComplete();
}
},
BackpressureStrategy.BUFFER);
}
...
@Test
public void testSseToFlowable() throws Exception {
final CountDownLatch latch = new CountDownLatch(3);
final AtomicInteger errors = new AtomicInteger(0);
WebTarget target = client.target(generateURL("/flowable/thing"));
SseEventSource msgEventSource = SseEventSource.target(target).build();
try (SseEventSource eventSource = msgEventSource)
{
eventSource.register(
event -> {thingList.add(event.readData(Thing.class, MediaType.APPLICATION_JSON_TYPE)); latch.countDown();},
ex -> errors.incrementAndGet());
eventSource.open();
boolean waitResult = latch.await(30, TimeUnit.SECONDS);
Assert.assertTrue("Waiting for event to be delivered has timed out.", waitResult);
Assert.assertEquals(0, errors.get());
Assert.assertEquals(eThingList, thingList);
}
}
</programlisting>
<para>
Here, an SSE client is connecting to a resource method that returns a <classname>Flowable</classname>.
Again, the server is sending character data, which is suitable for the SSE client, and the data looks
the same on the network.
</para>
</sect1>
<sect1>
<title>To stream or not to stream</title>
<para>
Whether or not it is appropriate to stream a list of values is a judgment call. Certainly, if the
list is unbounded, then it isn't practical, or even possible, perhaps, to collect the entire list
and send it at once. In other cases, the decision is less obvious.
</para>
<para>
<emphasis role="bold">Case 1.</emphasis> Suppose that all of the elements are producible quickly.
Then the overhead of sending them independently is probably not worth it.
</para>
<para>
<emphasis role="bold">Case 2.</emphasis> Suppose that the list is bounded but the elements will
be produced over an extended period of time. Then returning the initial elements when they become
available might lead to a better user experience.
</para>
<para>
<emphasis role="bold">Case 3.</emphasis> Suppose that the list is bounded and the elements can be
produced in a relatively short span of time but only after some delay. Here is a situation that
illustrates the fact that asynchronous reactive processing and streaming over the network are
independent concepts. In this case it's worth considering having the resource method return
something like <classname>CompletionStage<List<Thing>></classname> rather than
<classname>Flowable<List<Thing>></classname>. This has the
benefit of creating the list asynchronously but, once it is available, sending it to the client
in one piece.
</para>
</sect1>
</sect1>
<sect1>
<title>Proxies</title>
<para>
Proxies, discussed in <link linkend="proxies">RESTEasy Proxy Framework</link>, are a RESTEasy extension
that supports a natural programming style in which generic JAX-RS invoker calls are replaced by application
specific interface calls. The proxy framework is extended to include both
<classname>CompletionStage</classname> and the RxJava2 types <classname>Single</classname>,
<classname>Observable</classname>, and <classname>Flowable</classname>.
</para>
<para><emphasis role="bold">Example 1.</emphasis></para>
<programlisting>
@Path("")
public interface RxCompletionStageResource {
@GET
@Path("get/string")
@Produces(MediaType.TEXT_PLAIN)
public CompletionStage<String> getString();
}
@Path("")
public class RxCompletionStageResourceImpl {
@GET
@Path("get/string")
@Produces(MediaType.TEXT_PLAIN)
public CompletionStage<String> getString() { .... }
}
public class RxCompletionStageProxyTest {
private static ResteasyClient client;
private static RxCompletionStageResource proxy;
static {
client = new ResteasyClientBuilder().build();
proxy = client.target(generateURL("/")).proxy(RxCompletionStageResource.class);
}
@Test
public void testGet() throws Exception {
CompletionStage<String> completionStage = proxy.getString();
Assert.assertEquals("x", completionStage.toCompletableFuture().get());
}
}
</programlisting>
<para>
<emphasis role="bold">Example 2.</emphasis>
</para>
<programlisting>
public interface Rx2FlowableResource {
@GET
@Path("get/string")
@Produces(MediaType.TEXT_PLAIN)
@Stream
public Flowable<String> getFlowable();
}
@Path("")
public class Rx2FlowableResourceImpl {
@GET
@Path("get/string")
@Produces(MediaType.TEXT_PLAIN)
@Stream
public Flowable<String> getFlowable() { ... }
}
public class Rx2FlowableProxyTest {
private static ResteasyClient client;
private static Rx2FlowableResource proxy;
static {
client = new ResteasyClientBuilder().build();
proxy = client.target(generateURL("/")).proxy(Rx2FlowableResource.class);
}
@Test
public void testGet() throws Exception {
Flowable<String> flowable = proxy.getFlowable();
flowable.subscribe(
(String o) -> stringList.add(o),
(Throwable t) -> errors.incrementAndGet(),
() -> latch.countDown());
boolean waitResult = latch.await(30, TimeUnit.SECONDS);
Assert.assertTrue("Waiting for event to be delivered has timed out.", waitResult);
Assert.assertEquals(0, errors.get());
Assert.assertEquals(xStringList, stringList);
}
}
</programlisting>
</sect1>
<sect1>
<title>Adding extensions</title>
<para>
RESTEasy implements a framework that supports extensions for additional reactive classes. To understand
the framework, it is necessary to understand the existing support for <classname>CompletionStage</classname>
and other reactive classes.
</para>
<para>
<emphasis role="bold">Server side.</emphasis> When a resource method returns a
<classname>CompletionStage</classname>, RESTEasy subscribes to it using the class
<classname>org.jboss.resteasy.core.AsyncResponseConsumer.CompletionStageResponseConsumer</classname>.
When the <classname>CompletionStage</classname> completes, it calls
<methodname>CompletionStageResponseConsumer.accept()</methodname>, which sends the result back to
the client.
</para>
<para>
Support for <classname>CompletionStage</classname> is built in to RESTEasy, but it's not hard to extend
that support to a class like <classname>Single</classname> by providing a mechanism for transforming a
<classname>Single</classname> into a <classname>CompletionStage</classname>. In module resteasy-rxjava2,
that mechanism is supplied by <classname>org.jboss.resteasy.rxjava2.SingleProvider</classname>, which
implements interface <classname>org.jboss.resteasy.spi.AsyncResponseProvider<Single<?>></classname>:
</para>
<programlisting>
public interface AsyncResponseProvider<T> {
public CompletionStage toCompletionStage(T asyncResponse);
}
</programlisting>
<para>
Given <classname>SingleProvider</classname>, RESTEasy can take a <classname>Single</classname>,
transform it into a <classname>CompletionStage</classname>, and then use
<classname>CompletionStageResponseConsumer</classname> to handle the eventual value of
the <classname>Single</classname>.
</para>
<para>
Similarly, when a resource method returns a streaming reactive class like <classname>Flowable</classname>,
RESTEasy subscribes to it, receives a stream of data elements, and sends them to the client.
<classname>AsyncResponseConsumer</classname> has several supporting classes, each of which implements a
different mode of streaming. For example, <classname>AsyncResponseConsumer.AsyncGeneralStreamingSseResponseConsumer</classname>
handles general streaming and SSE streaming. Subscribing is done by calling
<methodname>org.reactivestreams.Publisher.subscribe()</methodname>, so a mechanism is needed
for turning, say, a <classname>Flowable</classname> into a <classname>Publisher</classname>.
That is, an implementation of <classname>org.jboss.resteasy.spi.AsyncStreamProvider<Flowable></classname>
is called for, where <classname>AsyncStreamProvider</classname> is defined:
</para>
<programlisting>
public interface AsyncStreamProvider<T> {
public Publisher toAsyncStream(T asyncResponse);
}
</programlisting>
<para>
In module resteasy-rxjava2, <classname>org.jboss.resteasy.FlowableProvider</classname> provides
that mechanism for <classname>Flowable</classname>. [Actually, that's not too hard since, in
rxjava2, a <classname>Flowable</classname> <emphasis>is</emphasis> a <classname>Provider</classname>.]
</para>
<para>
So, on the server side, adding support for other reactive types can be done by declaring a <code>@Provider</code> for the interface
<code>AsyncStreamProvider</code> (for streams) or <code>AsyncResponseProvider</code> (for single values), which
both have a single method to convert the new reactive type into (respectively) a <code>Publisher</code> (for streams)
or a <code>CompletionStage</code> (for single values).
</para>
<para>
<emphasis role="bold">Client side.</emphasis> The JAX-RS specification version 2.1 imposes two
requirements for support of reactive classes on the client side:
</para>
<orderedlist>
<listitem>support for <classname>CompletionStage</classname> in the form of
an implementation of the interface <classname>javax.ws.rs.client.CompletionStageRxInvoker</classname>, and
</listitem>
<listitem>
extensibility in the form of support for registering providers that implement
<programlisting>
public interface RxInvokerProvider<T extends RxInvoker> {
public boolean isProviderFor(Class<T> clazz);
public T getRxInvoker(SyncInvoker syncInvoker, ExecutorService executorService);
}
</programlisting>
Once an <classname>RxInvokerProvider</classname> is registered, an <classname>RxInvoker</classname>
can be requested by calling the <classname>javax.ws.rs.client.Invocation.Builder</classname> method
<programlisting>
public <T extends RxInvoker> T rx(Class<T> clazz);
</programlisting>
That <classname>RxInvoker</classname> can then be used for making an invocation that returns
the appropriate reactive class. For example,
<programlisting>
FlowableRxInvoker invoker = client.target(generateURL("/get/string")).request().rx(FlowableRxInvoker.class);
Flowable<String> flowable = (Flowable<String>) invoker.get();
</programlisting>
</listitem>
</orderedlist>
<para>
RESTEasy provides partial support for implementing <classname>RxInvoker</classname>s. For example,
<classname>SingleProvider</classname>, mentioned above, also implements
<classname>org.jboss.resteasy.spi.AsyncClientResponseProvider<Single<?>></classname>,
where <classname>AsyncClientResponseProvider</classname> is defined
</para>
<programlisting>
public interface AsyncClientResponseProvider<T> {
public T fromCompletionStage(CompletionStage<?> completionStage);
}
</programlisting>
<para>
<classname>SingleProvider</classname>'s ability to turn a <classname>CompletionStage</classname>
into a <classname>Single</classname> is used in the implementation of
<classname>org.jboss.resteasy.rxjava2.SingleRxInvokerImpl</classname>.
</para>
<para>
The same concept might be useful in implementing other <classname>RxInvoker</classname>s. Note,
though, that <classname>ObservableRxInvokerImpl</classname> and
<classname>FlowableRxInvokerImpl</classname> in module resteasy-rxjava2 are each derived
directly from the SSE implementation.
</para>
</sect1>
</chapter>
|