Home > Blockchain >  Modyfing data in an observable
Modyfing data in an observable

Time:04-06

I have the following observable: messages$: Observable<Message[] | undefined>. Message has 2 fields: id and content, both of which are string.

What I would like to do is to modify messages$ so that a function foo(string) is invoked on the content of each Message.

It doesn't seem difficult at face value but I'm new to observables and unfortunately I got stuck.

CodePudding user response:

I guess solution is simple:

messages$: Observable<Message[] | undefined> = yourSource
  .pipe(
    map(messages => {
      messages.forEach(value => {
        value.content = foo(value.content);
      });
      return messages;
    }
  )

CodePudding user response:

What you are asking is how can you change your Observable to an observable with sideeffect. You probably don't ever want that (except for simple cases like logging stuff).

Instead what you want to do is subscribe to that Observable and then do your logic in the subscription. That way you're also guaranteed that your logic is only run once (or the number you want) instead of being reliant on something else subscribing to the observable.

messages$.subscribe(({ content }) => { foo(content); });

Be careful of subscription that is not unsubscribed. Check out this question for a solution to that generic problem: RXJS - Angular - unsubscribe from Subjects

If i misunderstood your question, and what you really want is an observable that transforms the data, and your foo method is pure (does not modify the inputs or other external data), the solution is different:

const modifiedMessages$ = messages$.pipe(map(({ content }) => foo(content));
  • Related