Skip to content

Commit

Permalink
Fin de sección 10 | Uso de funciones de combinación
Browse files Browse the repository at this point in the history
  • Loading branch information
peteraraya committed Feb 10, 2020
1 parent 517ea46 commit 60ccecf
Show file tree
Hide file tree
Showing 8 changed files with 259 additions and 72 deletions.
18 changes: 18 additions & 0 deletions src/combinacion/01-startWith-endWith.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { of } from 'rxjs';
import { startWith, endWith } from 'rxjs/operators';

const numeros$ = of(1,2,3).pipe(
startWith('a','b','c'), //esto lo hace antes que se emita los numeros
endWith('x','y','z')
);

numeros$.subscribe( console.log);

/**
*
==========================================================================================================================
Notas :
- el of por defecto es sincrono por ende el startWith y el endWith pueden ser sincronos también
=============================================================================================================================
**/
39 changes: 39 additions & 0 deletions src/combinacion/02-lab-startWith.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { ajax } from 'rxjs/ajax';
import { pipe } from 'rxjs';
import { startWith } from 'rxjs/operators';

// Refrencias
const loadingDiv = document.createElement('div');

loadingDiv.classList.add('loading');

loadingDiv.innerHTML = 'Cargando !!';

// Refrencias al body
const body = document.querySelector('body');


// Streams

ajax.getJSON('https://reqres.in/api/users/2?delay=3')
.pipe(
startWith(true)// esta cargando si
)
.subscribe( resp => {
if ( resp === true) {
body.append(loadingDiv); // cuando está cargando va a mostrar esto
}else{
document.querySelector('.loading').remove(); // elimino cualquier elemento que tenga una clase loading
}
console.log(resp);
});


/**
*
==========================================================================================================================
Notas :
-
=============================================================================================================================
**/
21 changes: 21 additions & 0 deletions src/combinacion/03-concat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { interval, concat, of } from 'rxjs';
import { take } from 'rxjs/operators';


const interval$ = interval(1000);

concat(
interval$.pipe( take(3) ),
interval$.pipe( take(2)),
of(1)
)
.subscribe(console.log)

/**
*
==========================================================================================================================
Notas : función concat()
-
=============================================================================================================================
**/
23 changes: 23 additions & 0 deletions src/combinacion/04-merge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { fromEvent, merge } from 'rxjs';
import { pluck } from 'rxjs/operators';
// operadormerge obsoleto, recordar que está es una función


const keyup$ = fromEvent( document, 'keyup');
const click$ = fromEvent( document, 'click');

merge(
keyup$.pipe(pluck('type')),
click$.pipe(pluck('type'))
)

.subscribe( console.log);

/**
*
==========================================================================================================================
Notas :
-
=============================================================================================================================
**/
49 changes: 49 additions & 0 deletions src/combinacion/05-combineLastest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { fromEvent, merge, combineLatest } from 'rxjs';
import { pluck } from 'rxjs/operators';
// operadormerge obsoleto, recordar que está es una función


// const keyup$ = fromEvent(document, 'keyup');
// const click$ = fromEvent(document, 'click');

// combineLatest(
// keyup$.pipe(pluck('type')),
// click$.pipe(pluck('type'))
// )

// .subscribe(console.log);


const input1 = document.createElement('input');
const input2 = document.createElement('input');

input1.placeholder='[email protected]';

input2.placeholder='*************';
input2.type='password';

document.querySelector('body').append(input1, input2);

// Helpers

const getInputStream = (elemn:HTMLElement )=>
fromEvent<KeyboardEvent>(elemn, 'keyup').pipe(
pluck<KeyboardEvent,string>('target','value')
)


combineLatest(
getInputStream(input1),
getInputStream(input2),
).subscribe(console.log)



/**
*
==========================================================================================================================
Notas :
-
=============================================================================================================================
**/
51 changes: 51 additions & 0 deletions src/combinacion/06-forkJoin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { of, interval, forkJoin } from 'rxjs';
import { take, delay } from 'rxjs/operators';

const numeros$ = of(1,2,3,4);
const intervalo$ = interval(1000).pipe( take(3)); // 0..1..2
const letras$ = of('a','b','c').pipe( delay(3500));


// forkJoin( // retorna un obserble
// numeros$,
// intervalo$,
// letras$
// ).subscribe(console.log);

// otra forma
// forkJoin( // retorna un obserble
// numeros$,
// intervalo$,
// letras$
// ).subscribe(resp => {
// console.log('numeros:',resp[0]);
// console.log('intervalo:', resp[1]);
// console.log('letras:', resp[2]);
// });


// otra forma --> para verlo como objeto
// forkJoin({ // retorna un obserble
// numeros$,
// intervalo$,
// letras$
// }).subscribe(resp => {
// console.log(resp);
// });

// Nombres personalizados
forkJoin({ // retorna un obserble
num: numeros$,
int: intervalo$,
let: letras$
}).subscribe(resp => {
console.log(resp);
});
/**
*
==========================================================================================================================
Notas :
-
=============================================================================================================================
**/
33 changes: 33 additions & 0 deletions src/combinacion/07-lab-forkJoin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { forkJoin, of } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { catchError } from 'rxjs/operators';


const GITHUB_API_URL = 'https://api.github.com/users';
const GITHUB_USER = 'peteraraya';

forkJoin({
// url para obtener toda la informació del usuario de github
usuario: ajax.getJSON(
`${GITHUB_API_URL}/${GITHUB_USER}`
),
repos: ajax.getJSON(
`${GITHUB_API_URL}/${GITHUB_USER}/repos`
),
gists: ajax.getJSON(
`${GITHUB_API_URL}/${GITHUB_USER}/gists`
)
}).pipe(
catchError(err=>of(err.message))
)
.subscribe(console.log);

/**
*
==========================================================================================================================
Notas : Caso de uso más común del forkJoin()
- Realizar peticiones ajax de manera simultanea
-
=============================================================================================================================
**/
97 changes: 25 additions & 72 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,80 +1,33 @@
import { fromEvent, of } from 'rxjs';
import { tap, map, mergeMap, pluck, catchError, switchMap, exhaustMap } from 'rxjs/operators';
import { forkJoin, of } from 'rxjs';
import { ajax } from 'rxjs/ajax';


// Helper

const peticionHttpLogin = (userPass) =>
ajax.post('https://reqres.in/api/login?delay=1', userPass)
.pipe(
pluck('response','token'),// capturo solo el token
catchError( err => of('xxx'))
)


// Creando HTML con js


// Formulario
const form = document.createElement('form');
const inputEmail = document.createElement('input');
const inputPass = document.createElement('input');
const submitBtn = document.createElement('button');


// Configuraciones a estos campos

inputEmail.type = 'email';
inputEmail.placeholder = 'Email';
inputEmail.value = '[email protected]';


inputPass.type = 'password';
inputPass.placeholder = 'Password';
inputPass.value = 'cityslicka';

submitBtn .innerHTML = 'Ingresar';


// insertando html
form.append( inputEmail, inputPass, submitBtn );

document.querySelector('body').append(form);

//prevenir refresh
//Streams

const submitForm$ = fromEvent<Event>(form, 'submit')
.pipe(
tap( ev => ev.preventDefault() ), // no modifica el flujo
map( ev => ({
email: ev.target[0].value,
password: ev.target[1].value
})),
// mergeMap( peticionHttpLogin )
//switchMap(peticionHttpLogin)
exhaustMap(peticionHttpLogin)
);
// necesitamos la subscripción
submitForm$.subscribe(token =>{
console.log(token);
})



import { catchError } from 'rxjs/operators';


const GITHUB_API_URL = 'https://api.github.com/users';
const GITHUB_USER = 'peteraraya';

forkJoin({
// url para obtener toda la informació del usuario de github
usuario: ajax.getJSON(
`${GITHUB_API_URL}/${GITHUB_USER}`
),
repos: ajax.getJSON(
`${GITHUB_API_URL}/${GITHUB_USER}/repos`
),
gists: ajax.getJSON(
`${GITHUB_API_URL}/${GITHUB_USER}/gists`
)
}).pipe(
catchError(err=>of(err.message))
)
.subscribe(console.log);

/**
*
==========================================================================================================================
Notas : Ejercicio de comparación entre el mergeMap, switchMap y exhaustMap
- Caso de uso real
- siempre que manejemos un servicio que no controlemos es necesario manejar el
- el mergeMap : emite todas las subcripciones
- el swtichMap : cancela cualquier otra subscripción pendiente y solo retorna la ultima
- el exhaustMap : emite solo la primera hasta que tenga la respuesta se dispara nuevamente
Notas : Caso de uso más común del forkJoin()
- Realizar peticiones ajax de manera simultanea
-
=============================================================================================================================
**/

0 comments on commit 60ccecf

Please sign in to comment.