RxJS sequence equivalent to promise.then()?

前端 未结 8 1388
南旧
南旧 2020-11-28 05:12

I used to develop a lot with promise and now I am moving to RxJS. The doc of RxJS doesn\'t provide a very clear example on how to move from promise chain to observer sequenc

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 05:20

    This is how I did it.

    Previously

      public fetchContacts(onCompleteFn: (response: gapi.client.Response) => void) {
        const request = gapi.client.people.people.connections.list({
          resourceName: 'people/me',
          pageSize: 100,
          personFields: 'phoneNumbers,organizations,emailAddresses,names'
        }).then(response => {
          onCompleteFn(response as gapi.client.Response);
        });
      }
    
    // caller:
    
      this.gapi.fetchContacts((rsp: gapi.client.Response) => {
          // handle rsp;
      });
    

    After(ly?)

    public fetchContacts(): Observable> {
        return from(
          new Promise((resolve, reject) => {
            gapi.client.people.people.connections.list({
              resourceName: 'people/me',
              pageSize: 100,
              personFields: 'phoneNumbers,organizations,emailAddresses,names'
            }).then(result => {
              resolve(result);
            });
          })
        ).pipe(map((result: gapi.client.Response) => {
          return result; //map is not really required if you not changing anything in the response. you can just return the from() and caller would subscribe to it.
        }));
      }
    
    // caller
    
    this.gapi.fetchContacts().subscribe(((rsp: gapi.client.Response) => {
      // handle rsp
    }), (error) => {
      // handle error
    });
    

提交回复
热议问题