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?