Commit 6f25eea8 authored by micha's avatar micha
Browse files

add state-management

parent 2901e7da
......@@ -205,6 +205,46 @@
}
}
}
},
"state-management": {
"projectType": "library",
"root": "projects/state-management",
"sourceRoot": "projects/state-management/src",
"prefix": "lib",
"architect": {
"build": {
"builder": "@angular-devkit/build-ng-packagr:build",
"options": {
"tsConfig": "projects/state-management/tsconfig.lib.json",
"project": "projects/state-management/ng-package.json"
},
"configurations": {
"production": {
"tsConfig": "projects/state-management/tsconfig.lib.prod.json"
}
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "projects/state-management/src/test.ts",
"tsConfig": "projects/state-management/tsconfig.spec.json",
"karmaConfig": "projects/state-management/karma.conf.js"
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"projects/state-management/tsconfig.lib.json",
"projects/state-management/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "Reactive-Architecture-and-UX-Patterns",
......
# CombiningStreams
This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 9.1.4.
## Code scaffolding
Run `ng generate component component-name --project combining-streams` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module --project combining-streams`.
> Note: Don't forget to add `--project combining-streams` or else it will be added to the default project in your `angular.json` file.
## Build
Run `ng build combining-streams` to build the project. The build artifacts will be stored in the `dist/` directory.
## Publishing
After building your library with `ng build combining-streams`, go to the dist folder `cd dist/combining-streams` and run `npm publish`.
## Running unit tests
Run `ng test combining-streams` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
[combining-streams.intro.md](./src/lib/combining-streams.intro.md)
# Combining Stream and Behavior
![Reactive Architecture and UX Patterns - Combining Stream and Behavior](./assets/images/Reactive-architecture-and-ux-patterns_angular_combining-streams-and-behavior_michael-hladky.png)
This set of lessons are all about combination operators.
As this course focuses on real-life use cases,
we will use these operators in the context of state derivation, data fetching and update behavior.
We will start with some snippets of code people normally use.
With our examples we will run into some problems with that simple approaches.
As we go, we learn how to solve them,
introduce more robust patterns and finally know all the does and donts of deriving state with combination operators.
![Reactive Architecture and UX Patterns - Combination Operators](./assets/images/Reactive-architecture-and-ux-patterns_angular_combination-operators-dark_michael-hladky.png)
## Combination Operators - Operator Matrix
To get a better understanding of the operators in that group we create a matrix.
The operator matrix is something I came up with to show the relations of the different
operators to each other and the similarities in behavior.
| creation | creation | operator | operator |
|----------------|----------------|-------------------|-------------|
| combineLatest | forkJoin | combineLatestWith | combineAll |
| zip | | zipWith | zipAll |
| | | withLatestFrom | |
## Combination Operators - Algebraic approach
Another learning too I use, to teach people a more efficient learning of operators is the "Algebraic approach".
I named it that way because it borrows concepts and thinking from one of the broad parts of mathematics, [Algebra](https://en.wikipedia.org/wiki/Algebra).
> Literally translated Algebra means "reunion of broken parts".
Understanding the different operators in terms of their "broken parts" is unequally more efficient and intuitive than learning them one by one based on their name.
The list of broken parts from the above set looks like this:
`combineLatest`, `forkJoin`, `zip`, `withLatestFrom`, `With`, `All`
If we understand every of those "broken parts" we are intuitively able to understand their "reunion", meaning the operators itself.
## Combination Operators - Exercise walk through
Within this set of lessons we will walk through the following exercises:
- [ ] We start we a simple setup where we derive data in our component directly over HTTP requests by using `forkJoin`
- with this architecture we realize, we quickly run into the problem of over-fetching
- [ ] To solve it we refactor the give HTTP service to get more control over when we fetch the data
- this reviles one of the special behaviours of `frokJoin` and we need to rethink it usage
- [ ] We learn the difference of `forkJoin` and `combineLatest`
- this knowledge helps us to refactor the service and component.
- [ ] As we go we start to introduce more features into our UI
- again we run into a problem, this time over-rendering.
- [ ] To understand the problem we learn about the terms `Normalized` and `Denormalized` data
- by using `zip` for our calculation we are able to solve the problem of over-rendering
- [ ] As it was quite technical so far we learn about `withLatestFrom` with a more playful example
- by doing so we understand the concept of `promary` and `secondary` streams
- [ ] With a fresh and open mine we think about those concepts in combination with a UX Pattern called `opt-in updates`
- to give a better experience to our users we implement this pattern in our example
# StateManagement
This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 9.1.6.
## Code scaffolding
Run `ng generate component component-name --project state-management` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module --project state-management`.
> Note: Don't forget to add `--project state-management` or else it will be added to the default project in your `angular.json` file.
## Build
Run `ng build state-management` to build the project. The build artifacts will be stored in the `dist/` directory.
## Publishing
After building your library with `ng build state-management`, go to the dist folder `cd dist/state-management` and run `npm publish`.
## Running unit tests
Run `ng test state-management` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../../coverage/state-management'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
{
"$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
"dest": "../../dist/state-management",
"lib": {
"entryFile": "src/public-api.ts"
}
}
\ No newline at end of file
{
"name": "state-management",
"version": "0.0.1",
"peerDependencies": {
"@angular/common": "^9.1.6",
"@angular/core": "^9.1.6",
"tslib": "^1.10.0"
}
}
\ No newline at end of file
/*
* Public API Surface of state-management
*/
export * from './lib/index';
import {Component, OnDestroy} from '@angular/core';
import {Subscription} from 'rxjs';
import {scan, shareReplay} from 'rxjs/operators';
import {SourceService} from './source.service';
@Component({
selector: 'composition',
template: `
<h2>Composition Handling</h2>
<label>Visible:</label>
<input type="checkbox" [(ngModel)]="visible"/><br/>
<div class="case-content" *ngIf="visible">
numberOfEmissions{{ composition1$ | async }}
</div>
`
})
export class StartCompositionComponent implements OnDestroy {
subscription = new Subscription();
visible = false;
hotComposition1$;
composition1$ = this.source.$.pipe(
scan(numOfEmissions => ++numOfEmissions, 0),
shareReplay(1)
);
constructor(private source: SourceService) {
// this.hotComposition1$ = this.composition1$.pipe(publishReplay(1)) as ConnectableObservable<any>
// this.subscription-handling = this.hotComposition1$.connect();
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
import {NgModule} from '@angular/core';
import {CommonModule} from "@angular/common";
import {RouterModule} from "@angular/router";
import {ROUTES} from "./composition.routes";
import {MatButtonModule} from "@angular/material/button";
import {MatListModule} from "@angular/material/list";
import {MatFormFieldModule} from "@angular/material/form-field";
import {FormsModule} from "@angular/forms";
import {MatInputModule} from "@angular/material/input";
import {StartCompositionComponent} from "./composition.component";
import {SolutionCompositionComponent} from "./solution.composition.component";
@NgModule({
declarations: [
StartCompositionComponent,
SolutionCompositionComponent
],
imports: [
CommonModule,
MatButtonModule,
MatListModule,
MatFormFieldModule,
MatInputModule,
FormsModule,
RouterModule.forChild(ROUTES)
]
})
export class CompositionModule {
}
import {StartCompositionComponent} from "./composition.component";
import {SolutionCompositionComponent} from "./solution.composition.component";
export const ROUTES = [
{
path: '',
children: [
{
path: '',
component: StartCompositionComponent
},
{
path: 'solution',
component: SolutionCompositionComponent
}
]
}
];
import {Component, OnDestroy} from '@angular/core';
import {Subject, Subscription} from 'rxjs';
import {scan} from 'rxjs/operators';
import {SourceService} from './source.service';
@Component({
selector: 'solution-composition',
template: `
<h2>Selection Handling</h2>
<div class="case-content">numberOfEmissions{{ selection1$ }}</div>
`
//providers: [SubscriptionHandlingService]
})
export class SolutionCompositionComponent implements OnDestroy {
subscription = new Subscription();
onDestroy$ = new Subject<void>();
selection1$ = this.source.$.pipe(scan(numOfEmissions => ++numOfEmissions, 0));
constructor(private source: SourceService) {
}
ngOnDestroy(): void {
this.onDestroy$.next();
}
}
import { Injectable, OnDestroy } from '@angular/core';
import { Subject, timer } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class SourceService {
values = new Subject();
$ = this.values.asObservable();
constructor() {
timer(0, 1000).subscribe(n => {
console.log('change');
this.values.next(n);
});
}
}
import {Injectable, OnDestroy} from '@angular/core';
import {Observable, Subject, Subscription} from 'rxjs';
import {mergeAll} from 'rxjs/operators';
@Injectable()
export class SubscriptionHandlingService implements OnDestroy {
subscription = new Subscription();
processes$ = new Subject();
constructor() {
this.subscription.add(this.processes$.pipe(mergeAll()).subscribe());
}
hold(o$: Observable<any>): void {
this.processes$.next(o$);
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment