> For the complete documentation index, see [llms.txt](https://odilbeks-organization.gitbook.io/angular-ustoz-shogirt/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://odilbeks-organization.gitbook.io/angular-ustoz-shogirt/rxjs-asoslari-reactive-programming.md).

# RxJS Asoslari (Reactive Programming)

### Mundarija

1. RxJs nima?
2. Observable
3. Subscribe va Memory leak
4. Subject va BehaviorSubject
5. Eng muhim operatorlar

{% embed url="<https://youtu.be/yLqo0liwGV0?t=1526>" %}

{% embed url="<https://www.youtube.com/watch?index=3&list=PLDeZJa125eSZlqoPU87dmTZUpexZGFlHs&v=BuPzUbEZacg>" %}

***

RxJS — bu asinxron ma'lumotlar bilan ishlash uchun juda kuchli vosita. Uni **"Ma'lumotlar oqimi konveyeri"** deb tasavvur qiling.

***

### 1. RxJS nima?

Tasavvur qiling, siz daryo bo'yida turibsiz. Daryodan har xil narsalar oqib kelmoqda (baliqlar, barglar, koptoklar).

* **Daryo** — bu **Observable** (ma'lumot oqimi).
* **Siz** — **Observer** (kuzatuvchisiz), chunki siz daryoni kuzatib turibsiz.
* **Baliq tutish** — bu **Operator**, ya'ni oqimdan faqat o'zingizga kerakli narsani saralab olish.

***

### 2. Observable (Kuzatiladigan oqim)

Observable — bu vaqt davomida bir nechta qiymatlarni yubora oladigan funksiya yoki obyekt.

#### Observable yaratishning 3 xil usuli:

1. **`of()`**: Tayyor qiymatlarni ketma-ket chiqaradi.
2. **`from()`**: Array yoki Promiseni oqimga aylantiradi.
3. **`interval()`**: Ma'lum vaqt oralig'ida (masalan, har 1 sekundda) son chiqaradi.

```tsx
import { of, from, interval } from 'rxjs';

// 1. Of: 1, 2, 3 ni ketma-ket chiqaradi
const numbers$ = of(1, 2, 3);

// 2. From: Array ichidagilarni bittalab chiqaradi
const fruits$ = from(['Olma', 'Banan', 'Uzum']);

// 3. Interval: Har 1 sekundda 0, 1, 2... deb sanaydi
const timer$ = interval(1000);
```

> Maslahat: O'zgaruvchi oxiriga $ belgisini qo'yish (masalan, data$) — bu uning Observable ekanligini anglatuvchi dasturchilar orasidagi kelishuvdir.

***

### 3. Subscribe va Memory Leak (Obuna bo’lish va xotira to'lib ketishi)

Observable'ni shunchaki yaratish kifoya qilmaydi, uni **eshitish** (subscribe) kerak. Lekin ehtiyot bo'ling: agar component yopilsa-yu, eshitish davom etsa, bu dasturni sekinlashtiradi.

Quyidagi kodni yozing va bu componentni biror routega ulang. So’ng bu component ichida boshqa routega navigatsiya qiling. Natjada ushbu componentdagi console.log baribir ishlab turganini gucohi bo’lasiz:

```tsx
import { DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

@Component({...})
export class MyComponent {
  private destroyRef = inject(DestroyRef);

  ngOnInit() {
    interval(1000
      .subscribe(count => console.log(count));
  }
}
```

Yangi Angularda buni quyidagicha yechish mumkin:

```tsx
import { DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

@Component({...})
export class MyComponent {
  private destroyRef = inject(DestroyRef); // Ushbu qator

  ngOnInit() {
    interval(1000)
      .pipe(takeUntilDestroyed(this.destroyRef)) // va ushbu qator kerak bo'ladi
      .subscribe(count => console.log(count));
  }
}
```

#### ✅ To'g'ri usul: Async Pipe

Yana bir boshqa yo'l `| async` pipe'dan foydalanishdir. U komponent yopilganda o'zi avtomatik "quloqni yopadi" (unsubscribe).

```html
<h2>Soni: {{ timer$ | async }}</h2>
```

> Eski Angular bo’yicha ngOnDestoryda subscription unsubscribe qilinar edi. Buni ham o’rganib qo’ysangiz ziyon qilmaydi:

```tsx
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-my-component',
  template: `...`
})
export class MyComponent implements OnInit, OnDestroy {
  private subscription: Subscription = new Subscription();
  
  constructor(private dataService: DataService) {}

  ngOnInit() {
    // Single subscription
    this.subscription = this.dataService.getData()
      .subscribe(data => {
        console.log(data);
      });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
```

***

### 4. Subject va BehaviorSubject (Ma'lumot tarqatuvchilar)

Oddiy Observable faqat bitta yo'nalishda ishlaydi. **Subject** esa ham ma'lumot qabul qiladi, ham tarqatadi (Radio stansiya kabi).

| **Tur**             | **Xususiyati**                                                                                |
| ------------------- | --------------------------------------------------------------------------------------------- |
| **Subject**         | Faqat u ulangandan keyin kelgan xabarlarni eshitadi.                                          |
| **BehaviorSubject** | **Eng ko'p ishlatiladi.** Oxirgi xabarni eslab qoladi va yangi qo'shilganlarga darhol aytadi. |

**BehaviorSubject misolida State (holat) boshqarish:**

```tsx
// Service ichida
private status = new BehaviorSubject<string>("Onlayn");
currentStatus$ = this.status.asObservable();

changeStatus(newVal: string) {
  this.status.next(newVal); // Yangi qiymat yuborish
}
```

***

### 5. Eng muhim Operatorlar

Operatorlar — bu oqimdan kelayotgan ma'lumot ustida ishlash uchun kerak bo’ladi.

* **`map`**: Ma'lumotni o'zgartiradi (masalan, hamma sonni 2 ga ko'paytirish).
* **`filter`**: Keraksizlarini tashlab yuboradi.
* **`tap`**: Ma'lumotga tegmasdan, shunchaki konsolga chiqarish yoki log yozish uchun.
* **`debounceTime`**: Berilgan muddat davomida “uxlab” turadi

```tsx
import { map, filter, debounceTime } from 'rxjs/operators';

searchControl.valueChanges.pipe(
  debounceTime(500),         // 0.5 sekund kutish
  filter(text => text !== ''), // Bo'sh bo'lsa o'tkazma
  map(text => text.toUpperCase()), // Katta harfga o'tkaz
  tap((val) => console.log(val))
).subscribe();
```

***

### 🚀 Amaliy misol: Oddiy Counter Service

Bu misol orqali RxJS yordamida qanday qilib ma'lumotni komponentlar orasida almashishni ko'rishingiz mumkin.

**counter.service.ts**

```tsx
import { BehaviorSubject } from 'rxjs';

export class CounterService {
  private count = new BehaviorSubject<number>(0);
  count$ = this.count.asObservable(); // Komponentlar faqat o'qishi uchun

  increment() {
    this.count.next(this.count.value + 1);
  }
}
```

**app.component.html**

```html
<div>
  <h1>Hisoblagich: {{ counterService.count$ | async }}</h1>
  <button (click)="counterService.increment()">+1 qo'shish</button>
</div>
```

***

### 💡 Xulosa: Qoidalarni eslab qoling

1. Ma'lumot oqimi bilan ishlayapsizmi? **RxJS** ishlating.
2. Doim oxirgi qiymat kerakmi? **BehaviorSubject** tanlang.
3. Memory leak bo'lmasin desangiz? **Async pipe** ishlating.
4. Input qidiruv tizimi qilyapsizmi? **debounceTime** ni unutmang.

***

### Nazorat savollari

Bu savollarga o'zingiz tushunib, og'zaki javob berishga harakat qilib ko'ring:

1. **Observable** va **Subject** o'rtasidagi asosiy farq nimada?
2. Nima uchun biz `unsubscribe()` qilishimiz shart va `async pipe` bu muammoni qanday hal qiladi?
3. `BehaviorSubject` ning `Subject` dan afzalligi nimada?
4. `map` va `tap` operatorlarining vazifasi bir-biridan nima bilan ajralib turadi?

### Test

#### 1. RxJS eng to‘g‘ri qaysi ta’rifga mos keladi?

A) Faqat HTTP so‘rovlar uchun kutubxona

B) Ma’lumotlar oqimi bilan ishlash uchun asinxron kutubxona

C) CSS animatsiyalar uchun framework

D) Faqat backend uchun mo‘ljallangan vosita

✅ **Javob:** B

#### 2. Observable nimani anglatadi?

A) Faqat bitta qiymat qaytaradigan funksiya

B) Vaqt davomida bir nechta qiymat yuboradigan oqim

C) Oddiy obyekt

D) Faqat Promise o‘rnida ishlaydi

✅ **Javob:** B

***

#### 3. Quyidagilardan qaysi biri Observable yaratish funksiyasi EMAS?

A) `of()`

B) `from()`

C) `interval()`

D) `subscribe()`

✅ **Javob:** D

***

#### 4. `interval(1000)` Observable qanday ishlaydi?

A) 1 sekundda faqat bitta qiymat chiqaradi va to‘xtaydi

B) Har 1 sekundda 0, 1, 2, 3… sonlarini chiqaradi

C) Faqat juft sonlarni chiqaradi

D) 1000 ta qiymat chiqaradi

✅ **Javob:** B

***

#### 5. Observable nomi oxiriga `$` qo‘yish nimani bildiradi?

A) Majburiy sintaksis

B) Angular talabi

C) Bu o‘zgaruvchi Observable ekanini bildiruvchi kelishuv

D) Performance uchun kerak

✅ **Javob:** C

***

#### 6. Angular’da memory leak bo‘lmasligi uchun qaysi usul ENG xavfsiz?

A) `setTimeout` ishlatish

B) `unsubscribe()` ni unutish

C) `| async` pipe ishlatish

D) `console.log` qilish

✅ **Javob:** C

***

#### 7. Subject va BehaviorSubject orasidagi asosiy farq nima?

A) Subject tezroq ishlaydi

B) BehaviorSubject oxirgi qiymatni eslab qoladi

C) Subject faqat bitta komponentda ishlaydi

D) BehaviorSubject faqat backendda ishlaydi

✅ **Javob:** B

***

#### 8. Qaysi operator foydalanuvchi yozishni to‘xtatishini kutadi?

A) `map`

B) `filter`

C) `tap`

D) `debounceTime`

✅ **Javob:** D

***

#### 9. Observable ishlashi uchun subscribe bo‘lishi shart

✅ To‘g‘ri / ❌ Noto‘g‘ri

👉 **Javob:** ✅ To‘g‘ri

***

#### 10. Async pipe avtomatik unsubscribe qiladi

✅ To‘g‘ri / ❌ Noto‘g‘ri

👉 **Javob:** ✅ To‘g‘ri

***

#### 11. Oddiy Subject yangi qo‘shilgan subscriberga eski qiymatni yuboradi

✅ To‘g‘ri / ❌ Noto‘g‘ri

👉 **Javob:** ❌ Noto‘g‘ri

***

#### 12. `tap` operatori ma’lumotni o‘zgartiradi

✅ To‘g‘ri / ❌ Noto‘g‘ri

👉 **Javob:** ❌ Noto‘g‘ri

***

#### 13. Quyidagi kod nimani chiqaradi?

```tsx
of(1, 2, 3).pipe(
  map(x => x * 2)
).subscribe(console.log);
```

A) 1, 2, 3

B) 2, 4, 6

C) 1, 4, 9

D) Hech narsa chiqmaydi

✅ **Javob:** B

***

#### 14. Quyidagi kodda `filter` nima vazifani bajaryapti?

```tsx
of(1, 2, 3, 4).pipe(
  filter(x => x % 2 === 0)
)
```

A) Sonlarni ko‘paytiradi

B) Faqat juft sonlarni o‘tkazadi

C) Faqat toq sonlarni o‘tkazadi

D) Oqimni to‘xtatadi

✅ **Javob:** B

***

#### 15. BehaviorSubject nega state boshqarishda qulay?

A) Chunki u tez ishlaydi

B) Chunki oxirgi qiymatni saqlaydi

C) Chunki u faqat HTML’da ishlaydi

D) Chunki u subscribe talab qilmaydi

✅ **Javob:** B

> [QuizBot](https://t.me/QuizBot?start=pen8gwfv)

### Amaliy topshiriqlar

#### 1. "Aqlli Qidiruv" (Debounce Practice)

Bitta input yarating. Foydalanuvchi unga biror narsa yozsa, u yozishdan to'xtagandan keyin **600ms** o'tib, yozilgan so'z konsolga chiqsin.

> Agar yozilgan so'z 3 ta harfdan kam bo'lsa, konsolga chiqmasin (filter ishlating).

#### 2. "Raqamlar Fabrikasi" (Operator Practice)

`of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)` oqimidan foydalanib:

* Faqat toq sonlarni ajratib oling (`filter`).
* Har bir toq sonni kvadratga oshiring (`map`).
* Natijani ekranda ko'rsating.

#### 3. "Ranglar Servisi" (BehaviorSubject Practice)

Bitta `SettingsService` yarating. Unda `themeColor$` nomli `BehaviorSubject` bo'lsin (boshlang'ich qiymati 'white').

* Ikkita alohida komponent yarating.
* 1-komponentda rangni o'zgartiruvchi tugmalar bo'lsin (Qizil, Ko'k, Yashil).
* 2-komponent esa ushbu rangni o'zgarishini `async pipe` orqali eshitib tursin va o'zining `background-color`ini o'zgartirsin.

***

> **Darsdan namuna (takrorlash uchun):**

{% embed url="<https://youtu.be/Z1WTT4F1GZo>" %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://odilbeks-organization.gitbook.io/angular-ustoz-shogirt/rxjs-asoslari-reactive-programming.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
