RxJava is a lightweight open-source library, originally from Netflix, that makes it easy to compose asynchronous data sources and operations. This presentation is a high-level intro to this library and how it can fit into your application.
A presentation given to Overstock.com IT at annual conference. Twitter @TECHknO 2015. Goal of the presentation is to provide a good introduction to the reactive programming model with RxJava.
A practical guide to using RxJava on Android. Tips for improving your app architecture with reactive programming. What are the advantages and disadvantages of using RxJava over standard architecture? And how to connect with other popular Android libraries?
Presented at GDG DevFest The Netherlands 2016.
Intro to RxJava/RxAndroid - GDG Munich AndroidEgor Andreevich
The RX libraries have gained great popularity among developers lately. RX solves asynchronous programming elegantly based on the Observer pattern. This is especially helpful on Android where lots of interactions are asynchronous to the UI. Speaker: Egor Andreevici
An exploration into RxJava on Android for the experienced, yet uninitiated software engineer. This presentation explores Declarative vs Imperative programming paradigms and expands the discussion into Functional Reactive Programming. It explains the benefits of the observer contract, high-order functions, and schedulers available in RxJava. It also explains the purpose of the Android integration libraries: RxAndroid, RxLifecycle, and RxBindings.
Reactive Programming, Traits and Principles. What is Reactive, where does it come from, and what is it good for? How does it differ from event driven programming? It only functional?
After explaining what problem Reactive Programming solves I will give an introduction to one implementation: RxJava. I show how to compose Observable without concurrency first and then with Scheduler. I finish the talk by showing examples of flow control and draw backs.
Inspired from https://www.infoq.com/presentations/rxjava-reactor and https://www.infoq.com/presentations/rx-service-architecture
Code: https://github.com/toff63/Sandbox/tree/master/java/rsjug-rx/rsjug-rx/src/main/java/rs/jug/rx
Streams, Streams Everywhere! An Introduction to RxAndrzej Sitek
Nowadays users expect real time data - tweets, messages, order confirmations etc. - the user's attitude moved to the “push" model and it is high time for us devs to make that step as well.
Reactive Extensions (Rx) is the new hot stuff amongst developers these days. It is a library for composing asynchronous and event-based programs by using observable sequences. Sounds nice?
The only problem is that it can be a bit difficult to approach initially, especially when you come from an imperative world, but once mastered it helps dealing with some common problems in a nicer and cleaner way making your code more readable and easier to maintain.
Multiple implementations of Reactive Extensions helps reusing once learnt concepts between different programming languages. The aim of this talk is to provide a quick introduction to Rx theory and potential usecases. The examples are based on RxJava - the Java VM implementation of Reactive Extensions.
A practical guide to using RxJava on Android. Tips for improving your app architecture with reactive programming. What are the advantages and disadvantages of using RxJava over standard architecture? And how to connect with other popular Android libraries?
Presented at Droidcon Greece 2016.
Reactive Programming on Android - RxAndroid - RxJavaAli Muzaffar
Introduction to RxJava for reactive programming and how to use RxAndroid to do reactive programming on Android.
There is a sample android app to go with the slides that has all the source shown in the project.
RxJava maakt het mogelijk om gemakkelijk schaalbare code op een reactive manier te schrijven. Het kan echter ook een uitdaging zijn om de code leesbaar te maken, en kunnen debuggen wat er gebeurt. Deze sessie beschrijft onze ervaringen met het inzetten van RxJava als basis-onderdeel in onze codebase: een suite educatieve applicaties voor basis-, voortgezet- en beroepsonderwijs, grootschalig ingezet in vijf landen. Ruim tien agile teams werken samen aan deze op micro-services gebaseerde suite. RxJava heeft ons belangrijke voordelen gebracht. De introductie van dit nieuwe framework gaf ons ook verschillende verwachte uitdagingen en een paar interessante verrassingen. Deze sessie gaat in op de lessons learned en valkuilen waar je rekening mee kunt houden als je start met RxJava. Onder andere de volgende onderwerpen worden besproken: introduceren RxJava in bestaande codebase, stappen om als team RxJava te leren, hoe je een aantal standaard workflows effectief in RxJava kunt programmeren, foutafhandeling en debugging. Daarnaast wordt besproken hoe je RxJava kunt combineren met Java EE en Spring, en wat de voordelen kunnen zijn van RxJava in een enterprise applicatie.
A presentation given to Overstock.com IT at annual conference. Twitter @TECHknO 2015. Goal of the presentation is to provide a good introduction to the reactive programming model with RxJava.
A practical guide to using RxJava on Android. Tips for improving your app architecture with reactive programming. What are the advantages and disadvantages of using RxJava over standard architecture? And how to connect with other popular Android libraries?
Presented at GDG DevFest The Netherlands 2016.
Intro to RxJava/RxAndroid - GDG Munich AndroidEgor Andreevich
The RX libraries have gained great popularity among developers lately. RX solves asynchronous programming elegantly based on the Observer pattern. This is especially helpful on Android where lots of interactions are asynchronous to the UI. Speaker: Egor Andreevici
An exploration into RxJava on Android for the experienced, yet uninitiated software engineer. This presentation explores Declarative vs Imperative programming paradigms and expands the discussion into Functional Reactive Programming. It explains the benefits of the observer contract, high-order functions, and schedulers available in RxJava. It also explains the purpose of the Android integration libraries: RxAndroid, RxLifecycle, and RxBindings.
Reactive Programming, Traits and Principles. What is Reactive, where does it come from, and what is it good for? How does it differ from event driven programming? It only functional?
After explaining what problem Reactive Programming solves I will give an introduction to one implementation: RxJava. I show how to compose Observable without concurrency first and then with Scheduler. I finish the talk by showing examples of flow control and draw backs.
Inspired from https://www.infoq.com/presentations/rxjava-reactor and https://www.infoq.com/presentations/rx-service-architecture
Code: https://github.com/toff63/Sandbox/tree/master/java/rsjug-rx/rsjug-rx/src/main/java/rs/jug/rx
Streams, Streams Everywhere! An Introduction to RxAndrzej Sitek
Nowadays users expect real time data - tweets, messages, order confirmations etc. - the user's attitude moved to the “push" model and it is high time for us devs to make that step as well.
Reactive Extensions (Rx) is the new hot stuff amongst developers these days. It is a library for composing asynchronous and event-based programs by using observable sequences. Sounds nice?
The only problem is that it can be a bit difficult to approach initially, especially when you come from an imperative world, but once mastered it helps dealing with some common problems in a nicer and cleaner way making your code more readable and easier to maintain.
Multiple implementations of Reactive Extensions helps reusing once learnt concepts between different programming languages. The aim of this talk is to provide a quick introduction to Rx theory and potential usecases. The examples are based on RxJava - the Java VM implementation of Reactive Extensions.
A practical guide to using RxJava on Android. Tips for improving your app architecture with reactive programming. What are the advantages and disadvantages of using RxJava over standard architecture? And how to connect with other popular Android libraries?
Presented at Droidcon Greece 2016.
Reactive Programming on Android - RxAndroid - RxJavaAli Muzaffar
Introduction to RxJava for reactive programming and how to use RxAndroid to do reactive programming on Android.
There is a sample android app to go with the slides that has all the source shown in the project.
RxJava maakt het mogelijk om gemakkelijk schaalbare code op een reactive manier te schrijven. Het kan echter ook een uitdaging zijn om de code leesbaar te maken, en kunnen debuggen wat er gebeurt. Deze sessie beschrijft onze ervaringen met het inzetten van RxJava als basis-onderdeel in onze codebase: een suite educatieve applicaties voor basis-, voortgezet- en beroepsonderwijs, grootschalig ingezet in vijf landen. Ruim tien agile teams werken samen aan deze op micro-services gebaseerde suite. RxJava heeft ons belangrijke voordelen gebracht. De introductie van dit nieuwe framework gaf ons ook verschillende verwachte uitdagingen en een paar interessante verrassingen. Deze sessie gaat in op de lessons learned en valkuilen waar je rekening mee kunt houden als je start met RxJava. Onder andere de volgende onderwerpen worden besproken: introduceren RxJava in bestaande codebase, stappen om als team RxJava te leren, hoe je een aantal standaard workflows effectief in RxJava kunt programmeren, foutafhandeling en debugging. Daarnaast wordt besproken hoe je RxJava kunt combineren met Java EE en Spring, en wat de voordelen kunnen zijn van RxJava in een enterprise applicatie.
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...PROIDEA
Łukasz Nawojczyk
Language: Polish
Jakie są podejścia do programowania równoległego w Javie? Czy programowanie asynchroniczne musi być trudne w kodowaniu i debugowaniu? Czy można pisać współbieżny kod, który będzie łatwo testowalny? Czy asynchroniczność zawsze oznacza wielowątkowość?
W ramach wykładu zostaną przedstawione przykłady różnych podejść do wielowątkowości oraz wyniki analizy ogólnodostępnych rozwiązań, m.in. RxJava, JDeferred, Awaitility. Dodatkowo będzie omówione podejście do pisania wydajnych aplikacji internetowych w oparciu Vert.x i jego model obsługi współbieżności sterowany zdarzeniami.
The world of open source libraries and tools is vast for Android developers. Writing apps using solely Android SDK is impractical. Libraries can help you in many ways. They can speed up your development, save you creating boilerplate code and dealing with platform fragmentation, simplify your code and make it more readable and maintainable. In the talk I’m showing how several truly useful libraries can help a developer.
Presented at MobCon Europe 2017.
OSGi ecosystems compared on Apache Karaf - Christian Schneidermfrancis
OSGi Community Event 2015
A look at three competing OSGi ecosystems (Declarative Services, Blueprint, CDI). Capabilities of each DI framework. Comparison of support for EE technologies like JPA, Security, SOAP and REST services, UIs. Looking into some of the recent advancements like Aries JPA 2 featuring closure based transactions, JAAS Security, JSP and JSF on OSGi. Attendees will get a good overview about the stacks as well as recommendations where each is most applicable.
A smattering of brief intermediate topics regarding the Git version control system, including branching strategies, interactive rebasing, and migration from Subversion.
Letters from the Trenches: Lessons Learned Taking MongoDB to ProductionRick Warren
eHarmony moved one family of business-critical back-end applications to MongoDB several months ago. In this presentation, I discuss some of the important lessons we learned along the way about how to provision, scale, manage, and troubleshoot MongoDB.
These are slides from a talk I gave on 19 April, 2012, at the Object Management Group's (OMG's) Real-Time Workshop in Paris, France. The purpose of the talk was to describe the ways in which building applications is different from building platforms and systems, especially with respect to patterns of communication. Specifically, the recognized messaging patterns make sense at an application layer but are often too limiting and brittle within the software infrastructure itself.
Engineering Interoperable and Reliable SystemsRick Warren
The features of a communication technology that yield the properties of interoperability and reliability can be visualized in layers: technical (at the level of bytes), syntactic (at the level of messages), semantic (at the level of data, i.e. what the messages refer to), and so on. Real-world systems require at least data-level interoperability and reliability. The question is: will you acquire something that already supports those capabilities, or will you build it atop something that doesn't? This talk compares and contrasts DDS and AMQP as technology exemplars in each category.
Scaling DDS to Millions of Computers and DevicesRick Warren
I gave this presentation at an Object Management Group (OMG) workshop in Arlington, VA in March, 2010. It describes some of the concerns that will impact DDS as it is scaled to very large, geographically distributed systems. It also describes possible ways these challenges can be addressed.
This presentation gives a brief, semi-technical introduction to Data Distribution Service (DDS) technology from the Object Management Group. The focus is on the business benefits of the technology generally, not on RTI's implementation in particular.
Java 5 Language PSM for DDS: Final SubmissionRick Warren
This presentation describes the specification "Java 5 Language PSM for DDS." It was given to the MARS Task Force on Tuesday, December 7, 2010. The specification was recommended for adoption later in the week. The specification improves code portability, usability, and performance for applications that use Data Distribution Service (DDS) technology. See also http://code.google.com/p/datadistrib4j/.
Java 5 PSM for DDS: Revised Submission (out of date)Rick Warren
Presentation given to the Object Management Group's MARS Task Force in September, 2010 about a proposal to improve the Java API for the OMG's Data Distribution Service (DDS). See also http://code.google.com/p/datadistrib4j/.
This presentation is obsoleted by a later one: http://www.slideshare.net/rickbwarren/java-psm-revisedsubmission2presentationmars20101222.
Presentation from September, 2010 about the RTI proposal to improve the C++ API for the OMG's Data Distribution Service specification (DDS). See also http://code.google.com/p/dds-psm-cxx/.
Java 5 PSM for DDS: Initial Submission (out of date)Rick Warren
Presentation to the OMG's MARS Task Force in June, 2010 on proposed improvements to the Java API to the OMG's Data Distribution Service specification (DDS).
Large-Scale System Integration with DDS for SCADA, C2, and FinanceRick Warren
Presentation to the OMG Real-Time Workshop in May 2010 on system integration patterns, especially (but not exclusively) with respect to OMG Data Distribution Service (DDS) technology.
Data-Centric and Message-Centric System ArchitectureRick Warren
Presentation from April, 2010 summarizing the principles of data-centric design and how they apply to DDS technology. Message-centric design is presented by way of contrast.
Extensible and Dynamic Topic Types for DDSRick Warren
Presentation to the OMG MARS Task Force from March of 2010 on the "Extensible and Dynamic Topic Types for DDS" (DDS-XTypes) specification. Following this presentation, the Task Force voted to recommend the adoption of this specification.
Easing Integration of Large-Scale Real-Time Systems with DDSRick Warren
Webcast (sorry, audio not included) on system integration design patterns from July of 2010 pertaining mostly (but not exclusively) to Data-Distribution Service (DDS) technology.
Presentation to a Technical Meeting of the Object Management Group (OMG) proposing the issuance of an RFP for an improved Java API for DDS in December 2009. Following this presentation, the RFP was voted for issuance.
This presentation has been superseded by later ones on the same subject.
Presentation to the Robotics Task Force of the Object Management Group (OMG) introducing the members to the Data Distribution Service (DDS), another OMG-standard technology.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Building Scalable Stateless Applications with RxJava
1. Building Scalable Stateless Applications with RxJava
Rick Warren | Principal Engineer, eHarmony
rwarren@eharmony.com | @DangerLemming
2. RxJava
• Encapsulates data sequences: Observable
• Provides composable operations on them
• Abstracts away threading and synch
• Port from Microsoft .NET Reactive Extensions
• Java 6+, Groovy, Clojure, JRuby, Kotlin, and
Scala; Android-compatible
4. Applicability
Application or Presentation-Layer Service
Client Client Client Client Client
Data
Source
Data
Source
Data
Source
Data
Source
Data
Source
6. Streaming Queries
Data
Store Service Client
1 2 3
1. Query lots of data from NoSQL store
2. Enrich, filter, and score on the fly
3. Deliver “best” results to client
9. Streaming Queries
Iterables
Data
Store Client
Read
Enrich
Drain
Score
• Iterator pattern for fast start and lower footprint
• Composed as Decorators for flexibility
• Limitation: Doesn’t abstract timing, concurrency
10. Rate-Limited APIs
Scenario: Ingest data from
public API—they will refuse
rapid requests!
YouTube,
Facebook,
etc.
Your
Service
11. Rate-Limited APIs
YouTube,
Facebook,
etc.
Your
Service
Insight: The module responsible
for what data is available
is also responsible
for when data is available
12. Rate-Limited APIs
YouTube,
Facebook,
etc.
Your
Service
Solution: Facade API with
augmented Visitors to
encapsulate timing and retries
interface
DataVisitor<T>
extends
java.io.Closeable
{
void
accept(T
data);
}
Limitation: Scheduling
doesn't generalize
13. Using Futures
javax.ws.rs.client.Invocation
Response
invoke()
Future<Response>
submit()
• API and implementation cluttered with concurrency variants
• Caller responsible for concurrency, but has least information
• What can you do with a Future besides block?
14. Using Futures
What about Guava’s ListenableFuture?
ListeningExecutorService
service
=
MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
ListenableFuture<Explosion>
explosion
=
service.submit(new
Callable<Explosion>()
{
public
Explosion
call()
{
return
pushBigRedButton();
}
});
Futures.addCallback(explosion,
new
FutureCallback<Explosion>()
{
public
void
onSuccess(Explosion
explosion)
{
walkAwayFrom(explosion);
}
public
void
onFailure(Throwable
thrown)
{
battleArchNemesis();
}
});
• Requires access to ExecutorService!
• Still hard to compose
• Doesn’t generalize to multiple results
15. Make It
Work
Interactions should:
• Support multiple values
• Be efficient & incremental
• Encapsulate timing
• Compose operations
16. RxJava: Observable
• Like
Iterable,
but offers
fluent chaining
operations
• Like Stream,
but supports
async
termination and
error handling
17. Iterable Example
try
{
for
(E
elem
:
elements)
{
onNext(elem);
}
onCompleted();
}
catch
(Throwable
ex)
{
onError(ex);
}
19. Stream Example
try
{
elements.parallelStream()
Parallelize
operations
.filter(condition)
.map(transformation)
.forEach(elem
-‐>
onNext(elem));
onCompleted();
}
catch
(Throwable
ex)
{
onError(ex);
}
Still serial
20. Observable Example
elements
.filter(condition)
.map(transformation)
.subscribe(
elem
-‐>
onNext(elem),
ex
-‐>
onError(ex),
()
-‐>
onCompleted());
Fully
async’able
21. Creating an Observable
import
rx.*;
Observable<String>
o
=
Observable.just(
"a",
"b",
"c");
Iterable<String>
it
=
ImmutableList.of(
"a",
"b",
"c");
Observable<String>
o
=
Observable.from(it);
Future<String>
f
=
exec.submit(myTask);
Observable<String>
o
=
Observable.from(
f,
Schedulers.from(exec));
22. Example: JDBC
public
final
class
ObservableDB
{
private
final
DataSource
db;
public
ObservableDB(final
DataSource
source)
{
this.db
=
Objects.requireNonNull(source);
}
/**
Each
emitted
List
represents
a
row
in
the
ResultSet.
*/
public
Observable<List<Object>>
select(
final
String
sql,
final
Iterable<?>
params)
{
return
Observable.create(new
Observable.OnSubscribe<List<Object>>()
{
@Override
public
void
call(final
Subscriber<?
super
List<Object>>
sub)
{
//
...
}
});
}
}
23. Example: JDBC
@Override
public
void
call(final
Subscriber<?
super
List<Object>>
sub)
{
try
{
try
(Connection
cx
=
db.getConnection();
PreparedStatement
stmt
=
cx.prepareStatement(sql))
{
int
i
=
0;
for
(final
Object
p
:
params)
{
stmt.setObject(i++,
p);
}
try
(ResultSet
results
=
stmt.executeQuery())
{
while
(results.next()
&&
!sub.isUnsubscribed())
{
final
Lists<Object>
row
=
new
ArrayList<>();
for
(int
col
=
0;
col
<
results.getMetaData().getColumnCount();
++col)
{
row.add(results.getObject(col));
}
sub.onNext(row);
}
}
}
if
(!sub.isUnsubscribed())
{
sub.onCompleted();
}
}
catch
(final
Exception
ex)
{
if
(!sub.isUnsubscribed())
{
sub.onError(ex);
}
}
}
Serialize
Call n times
Call one or
the other,
once
24. Example: JDBC
public
void
printProductCatalog(
final
DataSource
source,
final
boolean
awesome)
{
ObservableDB
db
=
new
ObservableDB(source);
Subscription
subscription
=
db.select(
"SELECT
*
FROM
products
WHERE
isAwesome=?",
Collections.singleton(awesome))
//
Func1<List<Object>,
Product>
:
.map(unmarshallRowIntoProduct())
//
Func1<Product,
Observable<ProductWithPrice>>
:
.flatMap(remoteLookupPriceForProduct(this.priceService))
.take(NUM_PAGES
*
NUM_PRODUCTS_PER_PAGE)
.window(NUM_PAGES)
.subscribe(new
Observer<Observable<ProductWithPrice>>()
{
...
});
//
Some
time
later,
if
we
change
our
minds:
//subscription.unsubscribe();
}
interface
PriceService
{
Observable<ProductWithPrice>
getPrice(Product
p);
}
25. Example: JDBC
.subscribe(new
Observer<Observable<ProductWithPrice>>()
{
private
final
AtomicInteger
pageNumber
=
new
AtomicInteger(1);
@Override
public
void
onNext(final
Observable<ProductWithPrice>
page)
{
System.out.println("Page
"
+
pageNumber.getAndIncrement());
page.forEach(new
Action1<ProductWithPrice>()
{
@Override
public
void
call(final
ProductWithPrice
product)
{
System.out.println("Product:"
+
product);
}
});
}
@Override
public
void
onError(final
Throwable
ex)
{
System.err.println("This
is
how
you
handle
errors?
Srsly?");
}
@Override
public
void
onCompleted()
{
System.out.println("Copyright
2014
ACME
Catalog
Company");
}
});
31. Concurrency
1. Single-threaded and synchronous by default:
RxJava doesn’t magically create new threads for you
2. When creating an Observable, invoke Subscriber
from any thread you like (or use Actors, etc.)
3. Derive new Observables by binding subscription
and/or observation to Schedulers
33. What’s a Scheduler?
Policy for time-sharing among Workers
• Worker: Serial collection of scheduled Actions
• Action: Callable unit of work, e.g. Observable’s
subscription or notification
34. Built-in Schedulers
• Immediate—Schedulers.immediate()
• Run without scheduling in calling thread
• Trampoline—Schedulers.trampoline()
• Enqueue Actions in thread-local priority queue
• Computation—Schedulers.computation()
• Enqueue in event loop with as many threads as cores
35. Built-in Schedulers
• New Thread—Schedulers.newThread()
• Each Worker is a single-thread ExecutorService
• I/O—Schedulers.io()
• Mostly like New Thread, but with some pooling
• Executor Service—Schedulers.from(
ExecutorService)
• Bind new Scheduler to arbitrary ExecutorService, with
external serialization of Actions. Observations may hop
threads!
36. Bring Data to Calling Thread
Avoid whenever possible
myObservable.toBlocking()
Operations:
• first()
• last()
• toFuture()
• toIterable()