The document discusses the benefits of using RxJS observables over promises and events for managing asynchronous and reactive code in Angular applications. It explains key concepts like observers, subscriptions, operators, cold vs hot observables, and using RxJS with services and components. Example code is provided for creating observable data services to share data between components, composing asynchronous logic with operators, and best practices for managing subscriptions and preventing memory leaks. Overall, the document promotes a reactive programming style with RxJS for building maintainable and testable Angular applications.
Here I discuss about reactive programming, observable, observer and difference between observable and promise.
Also discuss some of important operators like forkJoin, switchMap, from, deboucneTime, discardUntilChanged, mergeMap. I discuss some of observable creation function.
As presented at DevDuck #6 - JavaScript meetup for developers (www.devduck.pl)
----
Looking for a company to build your app? - Check us out at www.brainhub.eu
Talk given at DevTeach Montreal on RxJS - The Basics & The Future.
Example repo: https://github.com/ladyleet/rxjs-test
Have questions? Find me on twitter http://twitter.com/ladyleet
Here I discuss about reactive programming, observable, observer and difference between observable and promise.
Also discuss some of important operators like forkJoin, switchMap, from, deboucneTime, discardUntilChanged, mergeMap. I discuss some of observable creation function.
As presented at DevDuck #6 - JavaScript meetup for developers (www.devduck.pl)
----
Looking for a company to build your app? - Check us out at www.brainhub.eu
Talk given at DevTeach Montreal on RxJS - The Basics & The Future.
Example repo: https://github.com/ladyleet/rxjs-test
Have questions? Find me on twitter http://twitter.com/ladyleet
Angular 2 is now in Beta. Reactive Programming techniques are used to write the Angular 2 framework. The same APIs and techniques are exposed to Angular 2 developers for application development.
This talk, by Geoff Filippi, will start with a brief overview of Reactive Programming. We will define and discuss the Observer Design Pattern. Observables are implemented in RxJS and are under consideration for standardization in ES2016. We will compare Observables, Promises, Events and callbacks. We will also discuss how Promises, Events and callbacks can be bridged into Observables.
Finally we will discuss how RxJS is used to implement Angular 2. We will explore how Observables are used in change detection and ngZone, Http, Async Facade and Forms. We will also discuss how to make use of RxJS and Observables in our Angular 2 applications.
This year ECMA International will be ratifying the biggest update to the JavaScript language in its history. In this talk we'll look at key features already appearing in browsers as well as those coming in the near future. We'll also explore how you can begin leveraging the power of ES6 across all browsers today. If you haven't looked at JavaScript recently, you soon realize that a bigger, better world awaits.
Explanation of the fundamentals of Redux with additional tips and good practices. Presented in the Munich React Native Meetup, so the sample code is using React Native. Additional code: https://github.com/nacmartin/ReduxIntro
Http Service will help us fetch external data, post to it, etc. We need to import the http module to make use of the http service. Let us consider an example to understand how to make use of the http service.
ECMAScript is the name of the international standard that defines JavaScript. ES6 → ECMAScript 2015. Latest ECMAScript version is ES7 which is ECMAScript 2016.
Basically it is a superset of es5
Introduction to React in combination with Redux. Redux helps you to develop applications in a simple way while having features like time-travel available during development.
Slides from the NestJS MasterClass.
We learned how to build JavaScript server-side applications with NestJS - A progressive NodeJS framework built with TypeScript.
You can find the code on GitHub:
https://github.com/nirkaufman/task-manager
Come see how easy it is to build fast, accurate, and responsive web UIs using the React library. Even if you’ve never written Javascript before, React’s straightforward syntax can get you started with your UI project quickly. In this session, you’ll learn about React’s declarative syntax and state representation, explore some of the basic components that are used to build sophisticated UIs, and leave with a foundational application you can continue to build on.
Understanding reactive programming with microsoft reactive extensionsOleksandr Zhevzhyk
We all want our applications to be responsible, reliable and testable. But event-driven paradigm sometimes could lead us to obscured or, even worse, messy code. Let’s look into the world, where generated data, background tasks and events are stuck together as asynchronous data streams to achieve a better result.
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020Matt Raible
Spring Boot is an efficient way to build Java applications with the Spring Framework. If you’re developing apps that handle sensitive data, you should make sure they’re secure.
This session will cover HTTPS, dependency checking, CSRF, using a CSP to prevent XSS, OIDC, password hashing, and much more!
You’ll learn how to add these features to a real application, using the Java language you know and love.
* Blog post: https://developer.okta.com/blog/2018/07/30/10-ways-to-secure-spring-boot
* Cheat sheet: https://snyk.io/blog/spring-boot-security-best-practices/
* OIDC demo: http://bit.ly/spring-oidc-demo
Angular 2 is now in Beta. Reactive Programming techniques are used to write the Angular 2 framework. The same APIs and techniques are exposed to Angular 2 developers for application development.
This talk, by Geoff Filippi, will start with a brief overview of Reactive Programming. We will define and discuss the Observer Design Pattern. Observables are implemented in RxJS and are under consideration for standardization in ES2016. We will compare Observables, Promises, Events and callbacks. We will also discuss how Promises, Events and callbacks can be bridged into Observables.
Finally we will discuss how RxJS is used to implement Angular 2. We will explore how Observables are used in change detection and ngZone, Http, Async Facade and Forms. We will also discuss how to make use of RxJS and Observables in our Angular 2 applications.
This year ECMA International will be ratifying the biggest update to the JavaScript language in its history. In this talk we'll look at key features already appearing in browsers as well as those coming in the near future. We'll also explore how you can begin leveraging the power of ES6 across all browsers today. If you haven't looked at JavaScript recently, you soon realize that a bigger, better world awaits.
Explanation of the fundamentals of Redux with additional tips and good practices. Presented in the Munich React Native Meetup, so the sample code is using React Native. Additional code: https://github.com/nacmartin/ReduxIntro
Http Service will help us fetch external data, post to it, etc. We need to import the http module to make use of the http service. Let us consider an example to understand how to make use of the http service.
ECMAScript is the name of the international standard that defines JavaScript. ES6 → ECMAScript 2015. Latest ECMAScript version is ES7 which is ECMAScript 2016.
Basically it is a superset of es5
Introduction to React in combination with Redux. Redux helps you to develop applications in a simple way while having features like time-travel available during development.
Slides from the NestJS MasterClass.
We learned how to build JavaScript server-side applications with NestJS - A progressive NodeJS framework built with TypeScript.
You can find the code on GitHub:
https://github.com/nirkaufman/task-manager
Come see how easy it is to build fast, accurate, and responsive web UIs using the React library. Even if you’ve never written Javascript before, React’s straightforward syntax can get you started with your UI project quickly. In this session, you’ll learn about React’s declarative syntax and state representation, explore some of the basic components that are used to build sophisticated UIs, and leave with a foundational application you can continue to build on.
Understanding reactive programming with microsoft reactive extensionsOleksandr Zhevzhyk
We all want our applications to be responsible, reliable and testable. But event-driven paradigm sometimes could lead us to obscured or, even worse, messy code. Let’s look into the world, where generated data, background tasks and events are stuck together as asynchronous data streams to achieve a better result.
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020Matt Raible
Spring Boot is an efficient way to build Java applications with the Spring Framework. If you’re developing apps that handle sensitive data, you should make sure they’re secure.
This session will cover HTTPS, dependency checking, CSRF, using a CSP to prevent XSS, OIDC, password hashing, and much more!
You’ll learn how to add these features to a real application, using the Java language you know and love.
* Blog post: https://developer.okta.com/blog/2018/07/30/10-ways-to-secure-spring-boot
* Cheat sheet: https://snyk.io/blog/spring-boot-security-best-practices/
* OIDC demo: http://bit.ly/spring-oidc-demo
This talk is a very quick intro to Docker, Terraform, and Amazon's EC2 Container Service (ECS). In just 15 minutes, you'll see how to take two apps (a Rails frontend and a Sinatra backend), package them as Docker containers, run them using Amazon ECS, and to define all of the infrastructure-as-code using Terraform.
Flask and Angular: An approach to build robust platformsAyush Sharma
AngularJS is a really powerful and extensible Javascript library that can be used for all number of applications. The team that up with Flask and you've got a great power and maintainability.
This is my presentation from TechBeats #3 hosted by Applause about Server-Side Swift framework called Vapor.
Swift is a great language and possibility of using it also in backend is a huge benefit for any iOS developer out there. Using Vapor is a seamless experience. With this framework creating advance APIs by iOS developer is as easy as writing simple iOS app.
https://www.meetup.com/TechBeats-hosted-by-Applause/events/254910023/
Python has been adding more and more async features to the language and the standard library. Starting with asyncio in python 3.4 and including the new async/await keywords in python 3.5, it’s difficult to understand how all these pieces fit together. More importantly, it’s hard to envision how to use these new language features in a real world application. In this talk we’re going to move beyond the basic examples of TCP echo servers and example servers that can add number together. Instead I’ll show you a realistic asyncio application. This application is a port of redis, a popular data structure server, written in python using asyncio. In addition to basic topics such as handling simple redis commands (GET, SET, RPUSH, etc), we’ll look at notifications using pub/sub, and how to implement blocking queues.
Burn down the silos! Helping dev and ops gel on high availability websitesLindsay Holmwood
HA websites are where the rubber meets the road - at 200km/h. Traditional separation of dev and ops just doesn't cut it.
Everything is related to everything. Code relies on performant and resilient infrastructure, but highly performant infrastructure will only get a poorly written application so far. Worse still, root cause analysis in HA sites will more often than not identify problems that don't clearly belong to either devs or ops.
The two options are collaborate or die.
This talk will introduce 3 core principles for improving collaboration between operations and development teams: consistency, repeatability, and visibility. These principles will be investigated with real world case studies and associated technologies audience members can start using now. In particular, there will be a focus on:
- fast provisioning of test environments with configuration management
- reliable and repeatable automated deployments
- application and infrastructure visibility with statistics collection, logging, and visualisation
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
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.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
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
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
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.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
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.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
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.
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
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.
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.
2. Multiple values over time
Cancellable with unsubscribe
Synchronous or asynchronous
Declarative: what, not how or when
Nothing happens without an observer
Separate chaining and subscription
Can be reused or retried
(not a spicy Promise)Observable
!! ! !!
3. Observable(lazy)
Promise(eager)
Create: new Observable((observer) => observer.next(123)); new Promise((resolve, reject) => resolve(123));
Transform: obs$.pipe(map((value) => value * 2)); promise.then((value) => value * 2);
Subscribe: sub = obs$.subscribe((value) => console.log(value)); promise.then((value) => console.log(value));
Unsubscribe: sub.unsubscribe(); // implied by promise resolution
https://angular.io/guide/comparing-observables#cheat-sheet
6. Observable
a function that takes
an Observer
const subscription = observable.subscribe(observer);
subscription.unsubscribe();
7. Observer
an object with next, error,
and complete methods
const observer = {
next: value => console.log('Next value:', value),
error: err => console.error('Error:', err),
complete: () => console.log('Complete')
};
const subscription = observable.subscribe(observer);
8. Subscription
an Observable only produces
values on subscribe()
A long time ago,
We used to be friends,
But I haven’t thought of
you lately at all...
16. @Injectable()
export class TodoStoreService {
private _todos: BehaviorSubject<Todo[]> = new BehaviorSubject([]);
constructor(private todoHTTP: TodoHttpService) {
this.loadData();
}
get todos(): Observable<Todo[]> {
return this._todos.asObservable();
}
loadData() {
this.todoAPI.getTodos()
.subscribe(
todos => this._todos.next(todos),
err => console.log('Error retrieving Todos’)
);
}
} https://github.com/sandikbarr/rxjs-todo/blob/master/src/app/todo/store/todo-store.service.ts
Store: Observable Data Service
Provide data to multiple parts of an application
17. BehaviorSubject
Just because you can access the value directly...
https://gist.github.com/sandikbarr/36bb0bf0b99a82a74be92aba1b1d0482#file-behavior-subject-getvalue-ts
const subject = new BehaviorSubject(initialValue);
// some time later…
const value = subject.getValue();
18. @Injectable()
export class TodoStoreService {
private _todo: BehaviorSubject<Todo[]> = new BehaviorSubject([]);
constructor(private todoAPI: TodoHttpService) {
this.loadData();
}
get todos(): Observable<Todo[]> {
return this._todos.asObservable();
}
}
https://github.com/sandikbarr/rxjs-todo/blob/master/src/app/todo/store/todo-store.service.ts
Protect the BehaviorSubject with
asObservable()
Components can subscribe after the data arrives
19. @Component({
selector: 'app-todo-list',
template: `
<ul>
<app-todo-list-item
*ngFor="let todo of todos"
[todo]="todo">
</app-todo-list-item>
</ul>
`
})
export class TodoListComponent implements OnInit, OnDestroy {
todos: Todo[];
todosSub: Subscription;
constructor (private todoStore: TodoStoreService) {}
ngOnInit() {
this.todosSub = this.todoStore.todos.subscribe(todos => {
this.todos = todos;
});
}
ngOnDestroy() {
this.todosSub.unsubscribe();
}
}
LET ME
HAVE THAT
TODO List
CLEAN UP
SUBSCRIPTIONS
20. @Component({
selector: 'app-todo-list',
template: `
<ul>
<app-todo-list-item
*ngFor="let todo of todos$ | async"
[todo]="todo">
</app-todo-list-item>
</ul>
`
})
export class TodoListComponent {
todos$: Observable<Todo[]> = this.todoStore.todos;
constructor (private todoStore: TodoStoreService) {}
}
USE THE ASYNC PIPE TO
AVOID MEMORY LEAKS
Subscriptions live until a stream is completed or until they are manually unsubscribed
https://github.com/sandikbarr/rxjs-todo/blob/master/src/app/todo/components/todo-list.component.ts
21. Decouple responsibilities
Observable Data Service
Provide data to multiple parts of an application
Not the same as centralized state management
Observable
Data SERVICE
HTTP SERVICE
COMPONENTS
!=
22. Action method updates the store on success
Store: Observable Data Service
https://github.com/sandikbarr/rxjs-todo/blob/master/src/app/todo/store/todo-store.service.ts
addTodo(newTodo: Todo): Observable<Todo> {
const observable = this.todoAPI.saveTodo(newTodo);
observable.pipe(
withLatestFrom(this.todos),
).subscribe(( [savedTodo, todos] ) => {
this._todos.next(todos.concat(savedTodo));
});
return observable;
}
24. @Injectable()
export class TodoHttpService {
base = 'http://localhost:3000/todos';
constructor(private http: HttpClient) { }
getTodos(): Observable<Todo[]> {
return this.http.get<Todo[]>(this.base);
}
saveTodo(newTodo: Todo): Observable<Todo> {
return this.http.post<Todo>(this.base, newTodo, {headers}).pipe(share());
}
}
share() makes a cold Observable hot
HTTP Service
https://github.com/sandikbarr/rxjs-todo/blob/master/src/app/todo/http/todo-http.service.ts
25. OPERATORS
Compose complex
asynchronous code in a
declarative manner
Pipeable Operators: take an input Observable and generate a resulting output Observable
Examples: filter, map, mergeMap
Creation Operators: standalone functions to create a new Observable
Examples: interval, of, fromEvent, concat
26. share() : refCount
share() also makes Observables retry-able
https://github.com/sandikbarr/rxjs-todo/blob/master/src/app/todo/http/todo-http.service.ts
@Injectable()
export class TodoHttpService {
base = 'http://localhost:3000/todos';
constructor(private http: HttpClient) { }
getTodos(): Observable<Todo[]> {
return this.http.get<Todo[]>(this.base);
}
saveTodo(newTodo: Todo): Observable<Todo> {
return this.http.post<Todo>(this.base, newTodo, {headers}).pipe(share());
}
}
27. " HOT: Share the execution
⛄ COLD: Invoke the execution
28. async : Unsubscribes automatically
https://gist.github.com/sandikbarr/36bb0bf0b99a82a74be92aba1b1d0482#file-duplicate-http-component-ts
But still be sure to avoid duplicating HTTP requests!
@Component({
selector: 'app-todo',
template: `
Total #: {{ total$ | async }}
<app-todo-list [todos]="todos$ | async"></app-todo-list>
`
})
export class DuplicateHttpTodoComponent {
todos$ = this.http.get<Todo[]>('http://localhost:3000/todos');
total$ = this.todos$.pipe(map(todos => todos.length));
constructor(private http: HttpClient) {}
}
29. ngIf with | async as
https://gist.github.com/sandikbarr/36bb0bf0b99a82a74be92aba1b1d0482#file-async-as-component-ts
Assign Observable values to a local variable
@Component({
selector: 'app-todo',
template: `
<ng-container *ngIf="todos$ | async as todos">
Total #: {{ todos.length }}
<app-todo-list [todos]="todos"></app-todo-list>
</ng-container>
`
})
export class TodoComponent {
todos$ = this.http.get<Todo[]>('http://localhost:3000/todos');
constructor(private http: HttpClient) {}
}
30. ngIf with| async as with ;ngElse
https://gist.github.com/sandikbarr/36bb0bf0b99a82a74be92aba1b1d0482#file-async-as-else-component-ts
Show alternate block when Observable has no value
@Component({
selector: 'app-todo',
template: `
<ng-container *ngIf="todos$ | async as todos; else loading">
Total #: {{ todos.length }}
<app-todo-list [todos]="todos"></app-todo-list>
</ng-container>
<ng-template #loading><p>Loading...</p></ng-template>
`
})
export class TodoComponent {
todos$ = this.http.get<Todo[]>('http://localhost:3000/todos');
constructor(private http: HttpClient) {}
}
47. // using map with nested subscribe
from([1, 2, 3, 4]).pipe(
map(param => getData(param))
).subscribe(val => val.subscribe(data => console.log(data)));
// using map and mergeAll
from([1, 2, 3, 4]).pipe(
map(param => getData(param)),
mergeAll()
).subscribe(val => console.log(val));
// using mergeMap
from([1, 2, 3, 4]).pipe(
mergeMap(param => getData(param))
).subscribe(val => console.log(val));
mergeMap()
Higher-order transformation operator
Luuk Gruijs: https://medium.com/@luukgruijs/understanding-rxjs-map-mergemap-switchmap-and-concatmap-833fc1fb09ff
Projects each source value into an Observable that is merged into the output Observable
48. Also provide the latest value from another Observable
withLatestFrom()
combineLatest()
Updates from the latest values of each input Observable
https://gist.github.com/sandikbarr/36bb0bf0b99a82a74be92aba1b1d0482#file-combinelatest-withlatestfrom-ts
combineLatest( [notifications$, otherPrimaryActiities$] )
.subscribe({
next: ( [notification, otherPrimaryActivity] ) => {
// fires whenever notifications$ _or_ otherPrimaryActivities$ updates
// but not until all sources have emitted at least one value
}
});
notifications$.pipe( withLatestFrom(mostRecentUpdates$) )
.subscribe({
next: ( [notification, mostRecentUpdate] ) => {
// fires only when notifications$ updates and includes latest from mostRecentUpdates$
}
});
52. catchError()
An error can terminate a stream and send the error to the error() callback,
or the stream can be allowed to continue if piped through catchError().
55. Custom Functions to Add and Remove Event Handlers
generate
interval
fromEventPattern
fromEvent
Create a New
Observable
Sequence
That Works Like a for-Loop
That Never Does Anything
That Repeats a Value
That Throws an Error
That Completes
From an Event
From a Promise
That Iterates
That Emits Values on a Timer
Decided at Subscribe Time
Based on a Boolean Condition
Over Values in a Numeric Range
Over Values in an Iterable or Array-like Sequence
Over Arguments
With an Optional Delay
Using Custom Logic
Of Object Key/Values
repeat
throwError
EMPTY
NEVER
from
pairs
range
of
timer
iif
defer
usingThat Depends on a Resource
56. Troubleshooting
Has this Observable been
subscribed to?
How many Subscriptions
does this Observable have?
When does this Observable
complete? Does it complete?
Do I need to unsubscribe
from this Observable?