0

In my simple app I have FilterComponent, ListComponent and one service (I call it GithubService).

I need that search word typed in FilterComponent address via http to github and return results to ListComponent.

export class GithubService {
  baseUrlSearch ="https://api.github.com/search";       

 initResponse:IResponse = {total_count:0,incomplete_results:false,items:[]}

    //subject = new Subject<IResponse>();
    subject = new BehaviorSubject<IResponse>(this.initResponse);

   constructor(private http: HttpClient) {  }


public setSearch(newSearchText:string):void{
  if (newSearchText.length<=3) return;
  const url=`${this.baseUrlSearch}/users?q=${newSearchText}`;
  this.http.get<IResponse>(url).pipe(debounceTime(500)).subscribe(
    res=> this.subject.next(res));      
}
public getResults():Observable<IResponse>
{
 return  this.subject.asObservable();
}

// ListComponent class
export class ListComponent implements OnInit {

  response$: Observable<IResponse>;
  constructor (private service :GithubService)
  {}
  ngOnInit(): void {
    this.response$= this.service.getResults();
  }
}

What I'm unaware of is that service make subscription each time newSearchText is changed.

Should I stay still or refactor somehow, or maybe unsubscribe each time?

Rot-man
  • 18,045
  • 12
  • 118
  • 124
Lapenkov Vladimir
  • 3,066
  • 5
  • 26
  • 37
  • Http calls are cold observables : they emit their value, then they die. You don't need to unsubscribe from them. –  Mar 07 '19 at 09:32
  • I thought that cold observable emits all values when listener subscribe to it. I don't care any subscription on http? – Lapenkov Vladimir Mar 07 '19 at 09:35
  • Observables emit their values to observers when they are subscribed to. Hot observables are kept open (meaning you have to unsuscribe at some point to avoid leaks), but cold observables just die after emmitting their values. In the case of HTTP calls, that's a single value. [Plenty of articles exist online](https://netbasal.com/when-to-unsubscribe-in-angular-d61c6b21bad3?gi=8e587b7361e9) if you have time on your hands ! –  Mar 07 '19 at 09:37
  • Article is exactly what i need , thanks! – Lapenkov Vladimir Mar 07 '19 at 09:41

0 Answers0