Mateusz Gebroski
Mateusz Gebroski

Reputation: 1334

RxJS assign observable and get data in one stream

I am trying to assign Observable at first and then subscribe to its values. This code:

//assign observable
    this.messagesDataSource$ = this.messageService.getMessagesDataSource(this.messagesContainerTitle);

//subscribe to its values     
    this.messagesDataSource$.subscribe((messages: Message[]) => {
                            this.messagesArray = messages;
                        });

works fine but I don;t think if this is good approach.. I've tried to make this run with pipe() but still if there is no subscription data array will not be assigned. My third idea was to use map

this.messagesDataSource$ =
        this.messageService.getMessagesDataSource(this.messagesContainerTitle)
            .map(messages => this.messagesArray = messages)

but still no result. Can you give me any hint how to assign observable and then get its data in one stream?

EDIT

map() in a pipe is also not fired there:

this.messagesDataSource$ =
this.messageService.getMessagesDataSource(this.messagesContainerTitle)
            .pipe(
                map((messages) => {
                console.log('in pipe');
                return messages
            }))

Upvotes: 1

Views: 1342

Answers (1)

asimhashmi
asimhashmi

Reputation: 4378

Observables are lazy in the sense that they only execute values when something subscribes to it

In your second approach you are not subscribing to Observable that's why you are not getting any data. You will get data when you subscribe to it.

For the same reason, your map operator is also not working. the map operator will trigger when you subscribes to the Observable.

If you are not using messagesDataSource$ anywhere else in your code than you can omit the extra assignment and directly subscribe to the Observable returned.

this.messageService.getMessagesDataSource(this.messagesContainerTitle)
  .subscribe(messages => this.messagesArray = messages)

Or if you want to do this in view you can use async pipe which automatically subscribes to your Observable under the hood

Upvotes: 3

Related Questions