← Back to TypeScript Course | Chapter 16: Advanced Patterns | Lesson 4 of 7

Observer Pattern की जानकारी

Observer Pattern एक object को कई dependent objects को notify करने देता है जब इसकी state बदलती है। यह event systems, application state updates, और one-to-many communication के लिए उपयोगी है।
Syntax
typescript
interface Observer<T> {
  update(data: T): void;
}
class Subject<T> {
  private observers: Observer<T>[] = [];
  subscribe(o: Observer<T>) { this.observers.push(o); }
  notify(data: T) { this.observers.forEach(o => o.update(data)); }
}

Basic Observer

एक basic observer setup में एक subject होता है जो typed callback functions की एक list maintain करता है और जब भी कोई event या state change हो हर एक को call करता है, बदलने वाली चीज़ को इस पर react करने वाली चीज़ों से decouple करते हुए।

उदाहरण: Basic Observer

typescript
type Callback = (data: string) => void;
class Subject {
  private observers: Callback[] = [];
  subscribe(cb: Callback) { this.observers.push(cb); }
  notify(data: string) { this.observers.forEach((cb) => cb(data)); }
}
const subject = new Subject();
subject.subscribe((data) => console.log("Received:", data));
subject.notify("event fired");

Subscribe और Unsubscribe

Subscribe करना subject की internal list में एक typed callback जोड़ता है, जबकि unsubscribe करना इसे हटाता है — आमतौर पर subscribe से खुद एक cleanup function return करके ताकि callers को callback reference अलग से track न करना पड़े।

उदाहरण: Subscribe and Unsubscribe

typescript
type Callback = () => void;
class Subject {
  private observers: Callback[] = [];
  subscribe(cb: Callback): () => void {
    this.observers.push(cb);
    return () => {
      this.observers = this.observers.filter((o) => o !== cb);
    };
  }
}
const subject = new Subject();
const unsubscribe = subject.subscribe(() => console.log("notified"));
unsubscribe();
console.log("Unsubscribed");

Observers और State

State changes पर react करने वाले Observers आमतौर पर notify होने पर new state को एक typed argument के रूप में receive करते हैं, हर observer को independently state re-fetch करने के बजाय exactly क्या बदला उसके आधार पर खुद को update करने देते हुए।

उदाहरण: Observers and State

typescript
interface State { count: number; }
type Callback = (state: State) => void;
class Store {
  private observers: Callback[] = [];
  subscribe(cb: Callback) { this.observers.push(cb); }
  setState(state: State) { this.observers.forEach((cb) => cb(state)); }
}
const store = new Store();
store.subscribe((state) => console.log("New count:", state.count));
store.setState({ count: 5 });

Typed Event Objects

Observers को pass किए जाने वाले event object को type करना — loose, individual arguments pass करने के बजाय — बाद में observers को क्या मिलता है उसमें नए fields जोड़ना आसान बनाता है बिना हर मौजूदा observer की function signature तोड़े।

उदाहरण: Typed Event Objects

typescript
interface ClickEvent {
  x: number;
  y: number;
}
type Callback = (event: ClickEvent) => void;
class Subject {
  private observers: Callback[] = [];
  subscribe(cb: Callback) { this.observers.push(cb); }
  notify(event: ClickEvent) { this.observers.forEach((cb) => cb(event)); }
}
const subject = new Subject();
subject.subscribe((e) => console.log(e.x, e.y));
subject.notify({ x: 10, y: 20 });

Observer कब उपयोग करें

Observer pattern तब अपनाएं जब program के कई independent parts को एक ही event source पर react करना हो, जैसे UI components जिन्हें shared data बदलने पर सभी को update होना हो — एक single consumer के लिए, एक plain callback ज़्यादा simple है।

उदाहरण: When to Use Observer

typescript
type Callback = (value: number) => void;
class DataSource {
  private observers: Callback[] = [];
  subscribe(cb: Callback) { this.observers.push(cb); }
  update(value: number) { this.observers.forEach((cb) => cb(value)); }
}
const source = new DataSource();
source.subscribe((v) => console.log("Widget A:", v));
source.subscribe((v) => console.log("Widget B:", v));
source.update(42);
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Observers हटाना भूल जाना, जो उन्हें list में रखता है और memory leaks का कारण बनता है।
  2. Notify के दौरान observers array पर loop करते समय इसे mutate करना, इसलिए कुछ callbacks skip हो जाते हैं।
  3. notify को ऐसी data के साथ call करना जो callback के parameter type से match नहीं करती।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.