This document provides an overview of reactive programming with RxJava. It begins with introductions to reactive programming and RxJava. It then discusses operators like map, filter, and flatMap that allow transforming and combining observable streams. It covers topics like error handling, threading with schedulers, subscriptions, and backpressure. The document includes examples of how to use various RxJava operators and concepts like transforming streams, handling errors, and improving performance with techniques like throttling.
Microservices with Java, Spring Boot and Spring CloudEberhard Wolff
Spring Boot makes creating small Java application easy - and also facilitates operations and deployment. But for Microservices need more: Because Microservices are a distributed systems issues like Service Discovery or Load Balancing must be solved. Spring Cloud adds those capabilities to Spring Boot using e.g. the Netflix stack. This talks covers Spring Boot and Spring Cloud and shows how these technologies can be used to create a complete Microservices environment.
Spring Weblfux. I have given this talk several times but in San Antonio JUG is where I think I have explained better this topic. An introduction to the reactive concepts on how Spring and Project Reactor implement them for Reactive web with Spring Webflux.
Microservices with Java, Spring Boot and Spring CloudEberhard Wolff
Spring Boot makes creating small Java application easy - and also facilitates operations and deployment. But for Microservices need more: Because Microservices are a distributed systems issues like Service Discovery or Load Balancing must be solved. Spring Cloud adds those capabilities to Spring Boot using e.g. the Netflix stack. This talks covers Spring Boot and Spring Cloud and shows how these technologies can be used to create a complete Microservices environment.
Spring Weblfux. I have given this talk several times but in San Antonio JUG is where I think I have explained better this topic. An introduction to the reactive concepts on how Spring and Project Reactor implement them for Reactive web with Spring Webflux.
Introduction to the Spring Framework:
Generar description
IoC container
Dependency Injection
Beans scope and lifecycle
Autowiring
XML and annotation based configuration
Additional features
Spring MVC 3.0 Framework
Objective:
1. Introduce Spring MVC Module
2. Learn about Spring MVC Components (Dispatcher, Handler mapping, Controller, View Resolver, View)
Slides:
1. What Is Spring?
2. Why use Spring?
3. By the way, just what is MVC?
4. MVC Architecture
5. Spring MVC Architecture
7. Spring MVC Components
8. DispatcherServlet
9. DispatcherServlet Architecture.........
.........................................................
Servlet vs Reactive Stacks in 5 Use CasesVMware Tanzu
ROSSEN STOYANCHEV SPRING FRAMEWORK DEVELOPER
In the past year Netflix shared a story about upgrading their main gateway serving 83 million users from Servlet-stack Zuul 1 to an async and non-blocking Netty-based Zuul 2. The results were interesting and nuanced with some major benefits as well as some trade-offs. Can mere mortal web applications make this journey and moreover should they? The best way to explore the answer is through a specific use case. In this talk we'll take 5 common use cases in web application development and explore the impact of building on Servlet and Reactive web application stacks. For reactive programming we'll use RxJava and Reactor. For the web stack we'll pit Spring MVC vs Spring WebFlux (new in Spring Framework 5.0) allowing us to move easily between the Servlet and Reactive worlds and drawing a meaningful, apples-to-apples comparison. Spring knowledge is not required and not assumed for this session.
The Spring Framework has always embraced testing as a first class citizen. Spring-based components should be modular, easy to wire together via dependency injection, and therefore easy to test. In fact, when well designed following a POJO programming model, a component in a Spring application can be unit tested without using Spring at all. And when you take the step toward developing integration tests, Spring's testing support is there to make your job easy.
Join Spring Test component lead Sam Brannen in this talk to learn about the basics for Spring's unit and integration testing support. This talk will provide attendees an overview of the following topics: unit testing without Spring, integration testing with Spring, loading application contexts (with and without context hierarchies), injecting dependencies into tests, transaction management for tests, SQL script execution, testing Spring MVC and REST web applications, and more.
I talked about Vue.js at @agenciasomadev. In this talk I showed the basics about the Vue.js JavaScript Framework and it's simplicity. I hope you enjoy :)
In this slide, I have explained the History of Selenium in a story narrative manner:
Topics covered
- Selenium Core (JavaScriptTestRunner)
- Same Origin Policy
- Selenium RC
- Selenium Grid
- Selenium IDE
- Selenium 1
- Selenium WebDriver
- Selenium 2
- Selenium 3
- New Selenium IDE
- Future versions of Selenium
- People behind Selenium
Java 8 Stream API. A different way to process collections.David Gómez García
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
Talk given at Typeform for the Barcelona Bug busters meetup.
How to Automate API Testing guides you through a possible API Testing workflow for API Functional Testing exploring different tools and approaches.
A simple tutorial for understanding the basics of angular JS. Very useful for the beginners. Also useful for the quick revision. Very attractive design for the tutorial of angular js.
Introduction to the Spring Framework:
Generar description
IoC container
Dependency Injection
Beans scope and lifecycle
Autowiring
XML and annotation based configuration
Additional features
Spring MVC 3.0 Framework
Objective:
1. Introduce Spring MVC Module
2. Learn about Spring MVC Components (Dispatcher, Handler mapping, Controller, View Resolver, View)
Slides:
1. What Is Spring?
2. Why use Spring?
3. By the way, just what is MVC?
4. MVC Architecture
5. Spring MVC Architecture
7. Spring MVC Components
8. DispatcherServlet
9. DispatcherServlet Architecture.........
.........................................................
Servlet vs Reactive Stacks in 5 Use CasesVMware Tanzu
ROSSEN STOYANCHEV SPRING FRAMEWORK DEVELOPER
In the past year Netflix shared a story about upgrading their main gateway serving 83 million users from Servlet-stack Zuul 1 to an async and non-blocking Netty-based Zuul 2. The results were interesting and nuanced with some major benefits as well as some trade-offs. Can mere mortal web applications make this journey and moreover should they? The best way to explore the answer is through a specific use case. In this talk we'll take 5 common use cases in web application development and explore the impact of building on Servlet and Reactive web application stacks. For reactive programming we'll use RxJava and Reactor. For the web stack we'll pit Spring MVC vs Spring WebFlux (new in Spring Framework 5.0) allowing us to move easily between the Servlet and Reactive worlds and drawing a meaningful, apples-to-apples comparison. Spring knowledge is not required and not assumed for this session.
The Spring Framework has always embraced testing as a first class citizen. Spring-based components should be modular, easy to wire together via dependency injection, and therefore easy to test. In fact, when well designed following a POJO programming model, a component in a Spring application can be unit tested without using Spring at all. And when you take the step toward developing integration tests, Spring's testing support is there to make your job easy.
Join Spring Test component lead Sam Brannen in this talk to learn about the basics for Spring's unit and integration testing support. This talk will provide attendees an overview of the following topics: unit testing without Spring, integration testing with Spring, loading application contexts (with and without context hierarchies), injecting dependencies into tests, transaction management for tests, SQL script execution, testing Spring MVC and REST web applications, and more.
I talked about Vue.js at @agenciasomadev. In this talk I showed the basics about the Vue.js JavaScript Framework and it's simplicity. I hope you enjoy :)
In this slide, I have explained the History of Selenium in a story narrative manner:
Topics covered
- Selenium Core (JavaScriptTestRunner)
- Same Origin Policy
- Selenium RC
- Selenium Grid
- Selenium IDE
- Selenium 1
- Selenium WebDriver
- Selenium 2
- Selenium 3
- New Selenium IDE
- Future versions of Selenium
- People behind Selenium
Java 8 Stream API. A different way to process collections.David Gómez García
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
Talk given at Typeform for the Barcelona Bug busters meetup.
How to Automate API Testing guides you through a possible API Testing workflow for API Functional Testing exploring different tools and approaches.
A simple tutorial for understanding the basics of angular JS. Very useful for the beginners. Also useful for the quick revision. Very attractive design for the tutorial of angular js.
FOR THE FULL VIDEO, RECORDING & PRESENTATION:
https://typesafe.com/blog/going-reactive-in-java-with-typesafe-reactive-platform
--
In this presentation by Jamie Allen, we do a deep dive into the Typesafe Reactive Platform from the Java developer’s perspective, to learn how Typesafe supports the entire Reactive application development lifecycle.
Reactive application development is becoming mainstream and considered a mission-critical need for future growth. This new wave of business applications are message-driven, elastic, resilient and responsive by nature, designed to scale elastically and maintain responsiveness during even large failures. With the Typesafe Reactive Platform (RP), including Play Framework and Akka, Java developers can start to use tools designed for building distributed systems that deliver highly-responsive user experiences. Regardless of whether you code in Java or Scala, Typesafe RP provides a resilient and message-driven application stack that scales effortlessly on multicore and cloud computing architectures.
IPT High Performance Reactive Programming with JAVA 8 and JavaScriptTrayan Iliev
Presentation @ jProfessionals BGJUG Conference
Sofia, November 22, 2015 by IPT – IT Education Evolved, High Performance Reactive Programming Workshop - Dec 15-17,2015 http://iproduct.org/en/course-reactive-java-js/
You are welcome to join us!
Low-latency, high-throughput reactive and functional programming in Java using Spring Reactor, RxJava, RxJS, Facebook React, Angular 2, Reactive Streams, Disruptor (ring buffer), Reactor & Proactor design patterns, benchmarking & comparison of concurrency implementations. December 15 - 17, 2015 - Workshop: High Performance Reactive Programming with JAVA 8 and JavaScript - http://iproduct.org/en/course-reactive-java-js/
Service Discovery using etcd, Consul and KubernetesSreenivas Makam
Overview of Service Discovery and Service Discovery using etcd, Consul, Kubernetes and Docker. Presented at Open source meetup, Bangalore(http://www.meetup.com/Bangalore-Open-Source-Meetup/events/229763724/)
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 pour Android : présentation lors du GDG Android MontréalSidereo
Reactive extensions are a framework created by Microsoft for .NET at the end of 2009.
It is a «library that allows programmers to write succinct declarative code to orchestrate and coordinate asynchronous and event-based programs »
The way you write code with this library might be referred to as functional reactive programming, we’ll talk more about this during the presentation.
It is now available for Java and Android. The specifics for Android are helpers for thread and UI stuff.
Jake Wharton is a huge contributor for the Android version
Rx is a generic abstraction of computation expressed through Observable<Element> interface, which lets you broadcast and subscribe to values and other events from an Observable stream.
Get ready to experience fast and scalable performance in your web applications as we dive into the world of Reactive Programming. Our guide using WebFlux is perfect for both beginners and experts a like.
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Elixir Club
Доповідь Максима Пугача, Team Lead/Software Engineer at LITSLINK, на Elixir Evening Club 3, Kyiv, 13.12.2018
Наступна конференція - http://www.elixirkyiv.club/
A boss of mine once told me "Just see, my poorly written Vert.x app outperforms my poorly written Elixir app". Now it is time to take up the gauntlet.
Cлідкуйте за нами у соцмережах @ElixirClubUA та #ElixirClubUA
Анонси та матеріали конференцій - https://www.fb.me/ElixirClubUA
Новини - https://twitter.com/ElixirClubUA
Фото та невимушена атмосфера - https://www.instagram.com/ElixirClubUA
*Канал організаторів мітапа - https://t.me/incredevly
I am Susan C. I am an Instant DBMS Homework Expert at databasehomeworkhelp.com. I hold a Master’s Degree in Programming, from Leeds, UK. I have been helping students with their homework for the past 9 years. I solve homework related to Instant DBMS.
Visit databasehomeworkhelp.com or email info@databasehomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with Instant DBMS Homework.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
4. 1.1. Side Effect.
• In computer science, a function or expression is said to have
a side effect if, in addition to returning a value, it also
modifies some state or has an observable interaction with
calling functions or the outside world.
• For example, a particular function might modify a global
variable or static variable, modify one of its arguments, raise
an exception, write data to a display or file, read data, or call
other side-effecting functions.
5. 1.2. Reactive
Programming.
• Reactive programming is programming with asynchronous data streams.
• Event buses or typical click events are really an asynchronous event stream, on which
you can observe and do some side effects.
• Reactive is that idea on steroids. You are able to create data streams of anything, not
just from click and hover events.
• It has many functions to combine, create and filter any of those streams.
• A stream can be used as an input to another one. Even multiple streams can be used
as inputs to another stream.
• You can merge two streams. You can filter a stream to get another one that has only
those events you are interested in. You can map data values from one stream to
another new one.
6.
7. • Each stream has many functions attached to it, such as map, filter, scan, etc. When
you call one of these functions, such as clickStream.map(f), it returns a new stream
based on the click stream. It does not modify the original click stream in any way. This
is a property called immutability.
8.
9. 2. Why should use
Reactive Programming.
2.1. Problems of Java Futures.
2.2. Problems of Callbacks.
2.3. Reactive.
11. • Java Futures are straight-forward to use for a
single level of asynchronous execution but they
start to add non-trivial complexity when they're
nested.
• Conditional asynchronous execution flows
become difficult to optimally compose (particularly
as latencies of each request vary at runtime) using
Futures. It can be done of course, but it quickly
becomes complicated (and thus error prone) or
prematurely blocks on 'Future.get()', eliminating
the benefit of asynchronous execution.
Link to demo.
12. 2.2. Problems of
Callbacks.
• Callbacks offer a solution to the tendency to block
on Future.get() by not allowing anything to block.
They are naturally efficient because they execute
when the response is ready.
• Similar to Futures though, they are easy to use
with a single level of asynchronous execution but
become unwieldy with nested composition.
Link to demo.
13. 2.3. Reactive.
• Reactive programming offers efficient execution and
composition by providing a collection of operators
capable of filtering, selecting, transforming, combining
and composing Observable's.
• The Observable data type can be thought of as a
"push" equivalent to Iterable which is "pull". With an
Iterable, the consumer pulls values from the producer
and the thread blocks until those values arrive. By
contrast with the Observable type, the producer
pushes values to the consumer whenever values are
available. This approach is more flexible, because
values can arrive synchronously or asynchronously.
14. • The following code demonstrates how a service layer method can choose
whether to synchronously return data from an in-memory cache or
asynchronously retrieve data from a remote service and callback with the
data once retrieved. In both cases the client code consumes it the same
way.
15.
16. • The following code demonstrates the consumption of an Observable API.
17. • That code is declarative and lazy as well as functionally "pure" in that no
mutation of state is occurring that would cause thread-safety issues.
• The API Service Layer is now free to change the behavior of the methods
'getListOfLists', 'getVideos', 'getMetadata', 'getBookmark' and 'getRating' –
some blocking others non-blocking but all consumed the same way.
• In the example, 'getListOfLists' pushes each 'VideoList' object via 'onNext()'
and then 'getVideos()' operates on that same parent thread. The
implementation of that method could however change from blocking to non-
blocking and the code would not need to change.
18. 3. RxJava.
3.1. The Basics.
3.2. Hello, World!
3.3. Introducing Transformation and Operators.
3.4. More on Operators.
3.5. Error Handling.
3.6. Schedulers.
20. 3.1. The Basics.
• The basic building blocks of reactive code are Observables and
Subscribers. An Observable emits items; a Subscriber
consumes those items.
• There is a pattern to how items are emitted. An Observable
may emit any number of items (including zero items), then it
terminates either by successfully completing, or due to an error.
• For each Subscriber it has, an Observable calls
Subscriber.onNext() any number of times, followed by either
Subscriber.onComplete() or Subscriber.onError().
• This looks a lot like your standard observer pattern, but it differs
in one key way - Observables often don't start emitting items
until someone explicitly subscribes to them.
22. Our Observable emits "Hello, world!" then completes. Now let's
create a Subscriber to consume the data:
23. Now that we've got myObservable and mySubscriber we can
hook them up to each other using subscribe():
24. RxJava has multiple built-in Observable creation methods for
common tasks. In this case, Observable.just() emits a single item then
completes, just like our code above:
Next, let's handle that unnecessarily verbose Subscriber. We don't
care about onCompleted() nor onError(), so instead we can use a
simpler class to define what to do during onNext():
25. Actions can define each part of a Subscriber. Observable.subscribe() can
handle one, two or three Action parameters that take the place of onNext(),
onError(), and onComplete(). Replicating our Subscriber from before looks like
this:
However, we only need the first parameter, because we're ignoring onError()
and onComplete():
26. Now, let's get rid of those variables by just chaining the method calls together:
Finally, let's use Java 8 lambdas to get rid of that ugly Action1 code.
27. 3.3. Introducing Transformation
and Operators.
Suppose I want to append my signature to the "Hello, world!" output. One
possibility would be to change the Observable:
This works if you have control over your Observable, but there's no guarantee
that will be the case - what if you're using someone else's library? Another
potential problem: what if I use my Observable in multiple places but only
sometimes want to add the signature?
28. 3.3. Introducing Transformation
and Operators.
How about we try modifying our Subscriber instead:
This answer is also unsatisfactory, but for different reasons: I want my
Subscribers to be as lightweight as possible because I might be running them
on the main thread. On a more conceptual level, Subscribers are supposed to
be the thing that reacts, not the thing that mutates.
Wouldn't it be cool if I could transform "Hello, world!" with some intermediary
step?
29. 3.3. Introducing Transformation
and Operators.
Operators can be used in between the source Observable and the ultimate
Subscriber to manipulate emitted items. RxJava comes with a huge collection
of operators, but its best to focus on just a handful at first.
For this situation, the map() operator can be used to transform one emitted item
into another:
30. 3.3. Introducing Transformation
and Operators.
map() does not have to emit items of the same type as the source Observable.
Suppose my Subscriber is not interested in outputting the original text, but
instead wants to output the hash of the text:
33. 3.4. More on Operators.
Suppose I have this method available:
34. 3.4. More on Operators.
I want to make a robust system for searching text and displaying the
results. Given what we know from the last article, this is what one
might come up with:
35. 3.4. More on Operators.
This answer is highly unsatisfactory because I lose the ability to
transform the data stream. If I wanted to modify each URL, I'd have to
do it all in the Subscriber. We're tossing all our cool map() tricks out
the window!
I could create a map() from urls -> urls, but then every map() call
would have a for-each loop inside of it.
36. 3.4. More on Operators.
There is a method, Observable.from(), that takes a collection of items
and emits each them one at a time:
That looks like it could help, let's see what happens:
37. 3.4. More on Operators.
I've gotten rid of the for-each loop, but the resulting code is a mess.
I've got multiple, nested subscriptions now! Besides being ugly and
hard to modify, it also breaks some critical as-yet undiscovered
features of RxJava. The way RxJava does error handling, threading,
and subscription cancellation wouldn't work at all with this code.
38. 3.4. More on Operators.
Observable.flatMap() takes the emissions of one Observable and
returns the emissions of another Observable to take its place. Here's
how it solves this problem:
39. 3.4. More on Operators.
Simplified with lambdas it looks awesome:
40. 3.4. More on Operators.
flatMap() can return any Observable it wants. Suppose I've got a
second method available:
Instead of printing the URLs, now I want to print the title of each
website received. But there's a few issues: my method only works on a
single URL at a time, and it doesn't return a String, it returns an
Observable that emits the String.
41. 3.4. More on Operators.
With flatMap(), solving this problem is easy; after splitting the list of
URLs into individual items, I can use getTitle() in flatMap() for each url
before it reaches the Subscriber:
42. 3.4. More on Operators.
And once more, simplified via lambdas:
43. 3.4. More on Operators.
We've only looked at two operators so far, but there are so many
more! How else can we improve our code?
getTitle() returns null if the URL 404s. We don't want to output "null"; it
turns out we can filter them out!
44. 3.4. More on Operators.
filter() emits the same item it received, but only if it passes the boolean
check.
And now we want to only show 5 results at most:
45. 3.4. More on Operators.
take() emits, at most, the number of items specified. (If there are fewer
than 5 titles it'll just stop early.)
Now we want to save each title to disk along the way:
46. 3.4. More on Operators.
doOnNext() allows us to add extra behavior each time an item is
emitted, in this case saving the title.
Link to other Operators.
47. 3.5. Error Handling.
Up until this point, we've largely been ignoring onComplete() and
onError(). They mark when an Observable is going to stop emitting
items and the reason for why (either a successful completion, or an
unrecoverable error).
Our original Subscriber had the capability to listen to onComplete()
and onError(). Let's actually do something with them:
49. 3.5. Error Handling.
• onError() is called if an Exception is thrown at any
time.
• The operators don't have to handle the Exception.
• You know when the Subscriber has finished
receiving items.
50. 3.6. Schedulers.
• You've got an Android app that makes a network
request. That could take a long time, so you load it
in another thread. Suddenly, you've got problems!
• Multi-threaded Android applications are difficult
because you have to make sure to run the right
code on the right thread; mess up and your app
can crash. The classic exception occurs when you
try to modify a View off of the main thread.
51. 3.6. Schedulers.
• In RxJava, you can tell your Observer code which thread to run on
using subscribeOn(), and which thread your Subscriber should run
on using observeOn():
52. 3.6. Schedulers.
• Everything that runs before my Subscriber runs on an I/O thread.
Then in the end, my View manipulation happens on the main
thread.
• The great part about this is that I can attach subscribeOn() and
observeOn() to any Observable! They're just operators! I don't have
to worry about what the Observable or its previous operators are
doing; I can just stick this at the end for easy threading.
53. 3.6. Schedulers.
You obtain a Scheduler from the factory methods described in the
Schedulers class.
• Schedulers.computation( ): meant for computational work such as
event-loops and callback processing; do not use this scheduler for
I/O (use Schedulers.io( ) instead); the number of threads, by
default, is equal to the number of processors.
• Schedulers.from(executor): uses the specified Executor as a
Scheduler.
• Schedulers.immediate( ): schedules work to begin immediately in
the current thread.
54. 3.6. Schedulers.
• Schedulers.io( ): meant for I/O-bound work such as asynchronous
performance of blocking I/O, this scheduler is backed by a thread-
pool that will grow as needed; for ordinary computational work,
switch to Schedulers.computation( ); Schedulers.io( ) by default is a
CachedThreadScheduler, which is something like a new thread
scheduler with thread caching.
• Schedulers.newThread( ): creates a new thread for each unit of
work.
• Schedulers.trampoline( ): queues work to begin on the current
thread after any already-queued work
55. 3.7. Subscriptions.
• When you call Observable.subscribe(), it returns a Subscription.
This represents the link between your Observable and your
Subscriber:
56. 3.7. Subscriptions.
• You can use this Subscription to sever the link later on:
• What's nice about how RxJava handles unsubscribing is that it
stops the chain. If you've got a complex chain of operators, using
unsubscribe will terminate wherever it is currently executing code3.
No unnecessary work needs to be done!
57. 3.8. Backpressure.
• In RxJava it is not difficult to get into a situation in which an
Observable is emitting items more rapidly than an operator or
subscriber can consume them. This presents the problem of what
to do with such a growing backlog of unconsumed items.
• The examples in this section will show how you might use such
operators to handle a bursty Observable like the one illustrated in
the following marble diagram:
• By fine-tuning the parameters to these operators you can ensure
that a slow-consuming observer is not overwhelmed by a fast-
producing Observable.
59. 3.8.1. Throttling.
• Operators like sample( ) or throttleLast( ), throttleFirst( ), and
throttleWithTimeout( ) or debounce( ) allow you to regulate the rate
at which an Observable emits items.
60. 3.8.1. Throttling.
Sample (or throttleLast):
The sample operator periodically "dips" into the sequence and emits
only the most recently emitted item during each dip:
62. 3.8.1. Throttling.
debounce (or throttleWithTimeout)
The debounce operator emits only those items from the source
Observable that are not followed by another item within a specified
duration:
63. 3.8.2. Buffers and
windows.
You can also use an operator like buffer( ) or
window( ) to collect items from the over-producing
Observable and then emit them, less-frequently, as
collections (or Observables) of items. The slow
consumer can then decide whether to process only
one particular item from each collection, to process
some combination of those items, or to schedule
work to be done on each item in the collection, as
appropriate.
64. 3.8.2. Buffers and
windows.
buffer
You could, for example, close and emit a buffer of items from the
bursty Observable periodically, at a regular interval of time:
65. 3.8.2. Buffers and
windows.
window
window is similar to buffer. One variant of window allows you to
periodically emit Observable windows of items at a regular interval of
time:
67. 3.8.2. Buffers and
windows.
You could also choose to emit a new window each time you have
collected a particular number of items from the source Observable:
68. 3.8.2. Buffers and
windows.
You could also choose to emit a new window each time you have
collected a particular number of items from the source Observable:
70. 3.9.1. The basics.
A Subject is a sort of bridge or proxy that acts both as an Subscriber
and as an Observable.
In this very basic example, I create a subject, subscribe to that subject
and then publish values to the sequence (by calling
subject.OnNext(T)).
If you have a Subject and you want to pass it along to some other
agent without exposing its Subscriber interface, you can mask it by
calling its asObservable method, which will return the Subject as a
pure Observable.
72. 3.9.2. AsyncSubject.
Subject that publishes only the last item observed to each Observer
that has subscribed, when the source Observable completes.
79. 3.9.6.
SerializedSubject.
Wraps a Subject so that it is safe to call its various on methods from
different threads.
When you use an ordinary Subject as a Subscriber, you must take
care not to call its Observer.onNext(T) method (or its other on
methods) from multiple threads, as this could lead to non-serialized
calls, which violates the Observable contract and creates an ambiguity
in the resulting Subject.
To protect a Subject from this danger, you can convert it into a
SerializedSubject with code like the following:
81. 4.1. Overview.
RxAndroid is an extension to RxJava built just for Android. It includes
special bindings that will make your life easier.
First, there's AndroidSchedulers which provides schedulers ready-
made for Android's threading system. Need to run some code on the
UI thread? No problem - just use AndroidSchedulers.mainThread():
82. 4.1. Overview.
If you've got your own Handler, you can create a scheduler linked to it
with HandlerThreadScheduler.
Next we have AndroidObservable which provides more facilities for
working within the Android lifecycle. There is bindActivity() and
bindFragment() which, in addition to automatically using
AndroidSchedulers.mainThread() for observing, will also stop emitting
items when your Activity or Fragment is finishing (so you don't
accidentally try to change state after it is valid to do so).
83. 4.1. Overview.
I also like AndroidObservable.fromBroadcast(), which allows you to
create an Observable that works like a BroadcastReceiver. Here's a
way to be notified whenever network connectivity changes:
84. 4.1. Overview.
Finally, there is ViewObservable, which adds a couple bindings for
Views. There's ViewObservable.clicks() if you want to get an event
each time a View is clicked, or ViewObservable.text() to observe
whenever a TextView changes its content.
85. 4.2. Retrofit.
There's one notable library that supports RxJava: Retrofit, a popular
REST client for Android. Normally when you define an asynchronous
method you add a Callback:
With RxJava installed, you can have it return an Observable instead:
86. 4.2. Retrofit.
Retrofit support for Observable also makes it easy to combine multiple
REST calls together. For example, suppose we have one call that gets
the photo and a second that gets the metadata. We can zip the results
together:
87. 4.3. Migrate old code to
Observable.
Observable.just() and Observable.from() are suffice for creating an
Observable from older code most of the time:
That works well if oldMethod() is fast, but what if it's slow? It'll block the
thread because you're calling oldMethod() before passing it to
Observable.just().
88. 4.3. Migrate old code to
Observable.
To get around that problem, here's a trick I use all the time - wrapping
the slower part with defer():
Now, the Observable returned won't call slowBlockingMethod() until
you subscribe to it.
89. 4.4. Lifecycle.
How do you handle the Activity lifecycle? There are two issues that
crop up over and over again:
1. Continuing a Subscription during a configuration change (e.g.
rotation). Suppose you make REST call with Retrofit and then want
to display the outcome in a ListView. What if the user rotates the
screen? You want to continue the same request, but how?
2. Memory leaks caused by Observables which retain a copy of the
Context. This problem is caused by creating a subscription that
retains the Context somehow, which is not difficult when you're
interacting with Views! If Observable doesn't complete on time, you
may end up retaining a lot of extra memory.
90. 4.4. Lifecycle.
The first problem can be solved with some of RxJava's built-in caching
mechanisms, so that you can unsubscribe/resubscribe to the same
Observable without it duplicating its work. In particular, cache() (or
replay()) will continue the underlying request (even if you
unsubscribe). That means you can resume with a new subscription
after Activity recreation:
91. 4.4. Lifecycle.
Note that we're using the same cached request in both cases; that way
the underlying call only happens once. Where you store request I
leave up to you, but like all lifecycle solutions, it must be stored
somewhere outside the lifecycle (a retained fragment, a singleton,
etc).
92. 4.4. Lifecycle.
The second problem can be solved by properly unsubscribing from
your subscriptions in accordance with the lifecycle. It's a common
pattern to use a CompositeSubscription to hold all of your
Subscriptions, and then unsubscribe all at once in onDestroy() or
onDestroyView():
94. 4.4. Lifecycle.
For bonus points you can create a root Activity/Fragment that comes
with a CompositeSubscription that you can add to and is later
automatically unsubscribed.
A warning! Once you call CompositeSubscription.unsubscribe() the
object is unusable, as it will automatically unsubscribe anything you
add to it afterwards! You must create a new CompositeSubscription as
a replacement if you plan on re-using this pattern later.
95. 5. Unit testing RxJava.
The ugly way
The first way is to simply subscribe in the same way we would from
outside the tests and then save the result in a global variable that can
later on be asserted.
For example, imagine we have a method in a database helper class
that is in charge of loading a user object.
96. 5. Unit testing RxJava.
Then the test for this method would look like this:
97. 5. Unit testing RxJava.
This code works because, by default, the Observable will run on the
same thread. Therefore, the assertion will always happen after the
result is set in the global variable.
98. 5. Unit testing RxJava.
The better way
Use static methods of a class called RxAssertions written by Software
Engineers at ribot.
99. 5. Unit testing RxJava.
The official way
Use TestSubscriber provided by RxJava.
Chaining assertions is not possible, because the assert methods don’t
return the TestSubscriber.
100. 6. References.
• Side effect (computer science) – Wikipedia.
• Referential transparency (computer science) – Wikipedia.
• The introduction to Reactive Programming you've been missing by André Staltz.
• Reactive Programming in the Netflix API with RxJava by Ben Christensen and Jafar Husain.
• Grokking RxJava by Dan Lew.
• Unit Testing RxJava Observables by Iván Carballo.
• Learning RxJava for Android by example by Kaushik Gopal.
• ReactiveX IO.
• Official RxJava’s Wiki.