Home > Blockchain >  how can i convert async/await code to rxjs(observable)?
how can i convert async/await code to rxjs(observable)?

Time:05-17

there are many codes in my projects that using async/await. but i want to exhange all them to rxjs code.

But I'm not used to rxjs. Please tell me about the pattern or method of converting the async/await code to rxjs. Or please recommend an example.

this is my original code (using async/await)

this.userHistory$ = new Subject(); 

async getUserStatue(userId, query){
  const userData = await this.UserApi.getUserInfo(userId, query);
  this.userHistory$.next(userData);
}

The code below is the code that I tried to convert using rxjs. Please give me some advice on this code.

getUserStatue(userId, query){
  from(this.UserApi.getUserInfo(userId, query)).subscribe(
    userData => this.userHistory$.next(userData);
  );
}

CodePudding user response:

You can directly return observable from the method you define and subscribe to it. Subscribe inside method is not as reusable and producing side effects.

getUserStatue(userId, query){
   return  from(this.UserApi.getUserInfo(userId, query))
}

usage

this.getUserState('abc','some query').subscribe(response=>....do something with response)

CodePudding user response:

The most direct translation is as follows:

this.userHistory$ = new Subject(); 

getUserStatue(userId, query){
  from(
    this.UserApi.getUserInfo(userId, query)
  ).subscribe(
    userData => this.userHistory$.next(userData)
  );
}

Of course, using a subject as an intermediary isn't nessesary. You can instead return an observable directly.

getUserStatue(userId, query){
  return from(this.UserApi.getUserInfo(userId, query));
}

Then instead of subscribing to userHistory$, you subscribe to the result of your function call getUserStatue(...)

  • Related