constructor() {
   this.errorObservable = Observable.create((observer:Observer<any>) => {
     this.errorObserver = observer;
   }).share();
 }
    constructor() {
        const MAX_NUM_ARRAY = 25;
        const MS_LIMIT = 1000;
        const MS_INTERVAL_SOURCE = 10;
        const MS_INTERVAL_ARRAY = 1;
        
        console.clear();
        
        let i = 0;
        let timerSource = Observable.create((observer) =>{
        
            let idInterval = setInterval(() => {
                observer.next(i++);
                if(i >= MS_LIMIT) observer.complete();
            }, MS_INTERVAL_SOURCE);
            
            return () => {
                clearInterval(idInterval);
            };
        });
        
        let arrayStrem = Observable.create((observer) => {
           let myVet = Array.from(Array(MAX_NUM_ARRAY).keys());
           
            let idInterval = setInterval(() => {
                myVet[Math.floor(Math.random() * (MAX_NUM_ARRAY - 0)) + 0] = new Date().getMilliseconds();
                observer.next(myVet);
                if(i >= MS_LIMIT) observer.complete();
            }, MS_INTERVAL_ARRAY);
            
            return () => {
                clearInterval(idInterval);
            };      
        });
        
       let result = timerSource
            .map(x => parseInt(x))
            .filter(x=> x % 2 === 0)
            .reduce(function (acc, x, idx, source) {
                return acc + x;
            }, 1);
            
       let scanSteram = timerSource
            .map(x => parseInt(x))
            .filter(x=> x % 2 === 0)
            .scan((a,c) => a + c, 1);     
        
      this.bindStream = arrayStrem;
            
            
      arrayStrem.subscribe(
            () => {},
            err => console.log(err),
            () => console.log('onComplete of arrayStrem', new Date().getMilliseconds())
        );      

       scanSteram.subscribe(
            (x:number) => (this.currentSum = x),
            err => console.log(err),
            () => console.log('onComplete of scanStream', new Date().getMilliseconds())
        );
        
       timerSource.subscribe(
            (x:number) => (this.currentValue = x),
            err => console.log(err),
            () => console.log('onComplete of mapper', new Date().getMilliseconds())
        );

       result.subscribe(
            x => console.log(x),
            err => console.log(err),
            () => console.log('onComplete of reduce', new Date().getMilliseconds())
        );


    }
Example #3
0
 private subscribeToSaveResponse(result: Observable<Tamanhos>) {
     result.subscribe((res: Tamanhos) =>
         this.onSaveSuccess(res), (res: Response) => this.onSaveError());
 }
Example #4
0
 private handleError (error: Response) {
     console.error(error);
     return Observable.throw(error.json().error || 'Server Error');
 }
 // Uses Observable.forkJoin() to run multiple concurrent http.get() requests.
 // The entire operation will result in an error state if any single request fails.
 getBooksAndMovies() {
     return Observable.forkJoin(
     this.http.get('/app/books.json').map((res:Response) => res.json()),
     this.http.get('/app/movies.json').map((res:Response) => res.json())
     );
 }
Example #6
0
function detectTrends(quote$: rx.Observable<Quote>) : rx.Observable<Trend>  {
  return rx.Observable.empty<Trend>();
}
 private subscribeToSaveResponse(result: Observable<PersonelHotpersonel>) {
     result.subscribe((res: PersonelHotpersonel) =>
         this.onSaveSuccess(res), (res: Response) => this.onSaveError(res));
 }
Example #8
0
 observable1 = constructorZone1.run(() => {
   return Rx.Observable.timer(10, 20);
 });
 .flatMap(s => {
     var url = "https://api.spotify.com/v1/search?type=artist&q=" + s;
     var promise = $.getJSON(url); // get the promise from getJSON
     return Observable.fromPromise(promise); // subscribe to the promise
 }); // flatMap flattens our Observable of Observables
Example #10
0
check() {
  return Observable.of(this.loggedIn);
  }
 get(id):Observable<Phone> {
   return Observable.of(xyzPhoneData());
 }
Example #12
0
function maptest(observable: Observable<number>): Observable<number> {
  return observable
    .map(value => value * 10)
    .filter(value => value > 10);
}
Example #13
0
 this.mission = route.params.flatMap(params => {
     if (params['id'] == "new") {
         return Observable.of(new Mission());
     }
     return missionService.get(params['id']);
 });
Example #14
0
import {Observable} from 'rxjs/Rx';
//import { Subject } from 'rxjs/Subject';

var button = document.getElementById('button');

var clicks = Observable.fromEvent(button, "click");



clicks.subscribe(
  (x) => alert("clicked"),
  (err) => alert("error"),
  () => alert('Completed')
);

 private handleError (error: Response, message: string) {
   return Observable.throw(this.messageService.error(message, error.json().message || error.json().error || 'Server error'));
 }
 private subscribeToData(): void {
     this.timerSubscription = Observable.timer(50)
         .subscribe(() => this.checkdeploy());
 }
Example #17
0
function parseRawStream(raw$: rx.Observable<string>) : rx.Observable<Quote>  {
  return rx.Observable.empty<Quote>();
}
 private subscribeToSaveResponse(result: Observable<Blog>, isCreated: boolean) {
     result.subscribe((res: Blog) =>
         this.onSaveSuccess(res, isCreated), (res: Response) => this.onSaveError(res));
 }
Example #19
0
function minFromPrevious(quote$: rx.Observable<Quote>, nbQuotes : number) : rx.Observable<number>  {
  return rx.Observable.empty<number>();
}
Example #20
0
 updateUserPrivate(userPrivate: UserPrivate): Observable<UserPrivate> {
   const { $key, ...unkeyedUser } = userPrivate;
   const setPromise = this.afDatabase.object(`usersPrivate/${$key}`).set(unkeyedUser);
   return Observable.fromPromise(setPromise).map(() => userPrivate);
 }
Example #21
0
 getArts() {
    return Observable.forkJoin(
        this.http.get('./app/ars.data.json').map((res:Response) => res.json()));
 }
	resolve(route:ActivatedRouteSnapshot):any {
		const id = route.params['id'];
		// console.log('Resolving a monster with id: ', id);
		return Observable.from(this.monsterService.get(id));
	}
 private _handleError(error: Response) {
   return Rx.Observable.throw(error || 'Server error');
 }
 .flatMap((payload) => {
   return Observable.fromPromise(payload.payload.openFin.displayCurrencyChart(payload.payload.symbol))
 })
Example #25
0
    public fetchPullRequestComments(pullRequest: PullRequest): Observable<Comment[]> {
        return Observable.create((observer: Observer<Comment[]>) => {
            if (this.authService.getToken() != null) {
                let headers = new Headers();
                headers.append('Authorization', `Bearer ${this.authService.getToken()}`);
                this.http.get(
                    this.repoUrl + '/pullrequests/' + pullRequest.id + '/comments?pagelen=100',
                    { headers: headers })
                    .map(res => res.json()).subscribe(commentContainer => {

                        // get first page of comments
                        let comments = commentContainer.values;

                        // Calc number of other pages to get
                        let nbPages = Math.ceil(commentContainer.size / commentContainer.pagelen);

                        if (nbPages <= 1) {
                            // Return the result to the observers
                            observer.next(comments);
                        }

                        // Build array of fetch to subscribe
                        let fetchPages: any[] = [];
                        for (let i = 2; i <= nbPages; i++) {
                            fetchPages.push(this.fetchPullRequestCommentsPage(pullRequest, i));
                        }

                        // get synchrone result of all fetch
                        Observable.forkJoin(fetchPages).subscribe(datas => {
                            let dataArray: any = datas;
                            dataArray.forEach((data: any) => {
                                comments = comments.concat(data.values);
                            },
                                (err: any) => {
                                    observer.error(err);
                                });

                            let modelComments: Comment[] = comments.map((jsonComment: any) => {
                                console.log(jsonComment);
                                let content: CommentContent = {
                                    html: jsonComment.content.html,
                                    markup: jsonComment.content.markup,
                                    raw: jsonComment.content.raw
                                };
                                let author: User = {
                                    userName: jsonComment.user.username,
                                    displayName: jsonComment.user.display_name,
                                    uuid: jsonComment.user.uuid
                                };
                                let comment: Comment = {
                                    content: content,
                                    author: author
                                };
                                return comment;
                            });

                            // Return the result to the observers
                            observer.next(modelComments);
                        },
                            (err) => {
                                observer.error(err);
                            },
                            () => {
                                observer.complete();
                            });
                    },
                    err => {
                        observer.error(err);
                    }
                    );
            } else {
                observer.error('no token');
            }
        });
    }
Example #26
0
 this.expert = route.params.flatMap( params => {
     if(params['id'] == "new") {
         return Observable.of(new Expert());
     }
     return expertService.get(params['id']);
 });
Example #27
0
// #docregion Observable
import 'rxjs/add/operator/map';

import {Observable, Subscriber} from 'rxjs/Rx';

var obs = new Observable<number>((obs: Subscriber<any>) => {
  var i = 0;
  setInterval(() => obs.next(++i), 1000);
});
obs.map((i: number) => `${i} seconds elapsed`).subscribe(msg => console.log(msg));
// #enddocregion
import { Observable } from 'rxjs/Rx';

Observable.range(1,10).filter(function(data){
    return data % 2 == 0; 
}).subscribe(function(data){
    console.log(data)
}, function(err){
    console.log(err)
}, function(){
    console.log('completed')
})
Example #29
0
 handleErrors(error: Response) {
   console.log(JSON.stringify(error.json()));
   return Observable.throw(error);
 }
 onError(callback:(err:any) => void) {
   this.errorObservable.subscribe(callback);
 }