Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Observable based on callback

I try to adjust a working example from ngx-chips to my needs. This is how the onRemoving method example looks like:

public onRemoving(tag: TagModel): Observable<TagModel> {
        const confirm = window.confirm('Do you really want to remove this tag?');
        return Observable
            .of(tag)
            .filter(() => confirm);
    }

Now instead of windows.confirm I want to use a custom component that has a AskQuestion method with the following signatur:

AskQuestion(question: string, yesCallback: () => void, noCallback?: () => void): void {

So now I have multiple callbacks but the ngx-chips components expect that I return an observable. I tried to convert the callback to an observable using the bindCallback method:

 public onRemoving(tag: TagModel): Observable<TagModel> {

    const choiceCallback = (choice: boolean): TagModel=> {
      if (choice)
        return tag;
    };

    this.questionService.AskQuestion("Remove item?", () => choiceCallback(true), () => choiceCallback(false))

    return Observable.bindCallback(choiceCallback);
  }

But it looks like I am doing it wrong. Any ideas?

like image 625
Martin Brandl Avatar asked May 23 '26 21:05

Martin Brandl


1 Answers

The definition of bindCallback() reads:

Give it a function f of type f(x, callback) and it will return a function g that when called as g(x) will output an Observable.

And your usage does not fit this description. choiceCallback() does not return a function that returns an observable.

Use an Observable constructor instead:

public onRemoving(tag: TagModel): Observable <TagModel> {

  return Observable.create(observer => {
    const choiceCallback = (choice: boolean) => {
      if (choice) {
        observer.next(tag);
      }
      observer.complete();
    };

    this.questionService.AskQuestion("Remove item?", () => choiceCallback(true), () => choiceCallback(false));
  });
}
like image 103
André Werlang Avatar answered May 26 '26 10:05

André Werlang