Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define the type of an observer in typescript

Typescript is asking me to type my observer variable :

Observer.create(observer: whatTypeShouldIUse => /* do things with observer */)

I tried using the Observer class or interface from the rxjs library, but it's a generic type.

What type should I put for my observer ? I put Observer<any> for now...

like image 921
Lev Avatar asked Feb 22 '17 14:02

Lev


People also ask

How do you use observer in typescript?

Observer is a behavioral design pattern that allows some objects to notify other objects about changes in their state. The Observer pattern provides a way to subscribe and unsubscribe to and from these events for any object that implements a subscriber interface.

What is an observable in typescript?

An Observable is a collection of multiple input values that get processed using array methods such as map , reduce , filter , and so on. It comes in handy when handling asynchronous operations such as making HTTP requests, user-input events, and so on.

What is observable observer?

Observer : Any object that wishes to be notified when the state of another object changes. Observable : Any object whose state may be of interest, and in whom another object may register an interest.

What is Observer pattern in angular?

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of state changes. This pattern is similar (but not identical) to the publish/subscribe design pattern.


1 Answers

In case you didn't find a solution yet. First, you must import both Observer and Observable libraries.

import { Observable, Observer } from 'rxjs';

Following your question, we do something like this:

Observable.create( (observer: Observer<JSON>) => {
    /* do things with observer */
    observer.next(data); //data - Must be a JSON object
    observer.complete();
})

Note that the observer type argument is the type of the observer.next(data).

like image 74
David Vale Avatar answered Sep 20 '22 11:09

David Vale