如何在不中断可观察流订阅的情况下向主题发送不同的可观察结果? [英] How to send to a Subject different Observable results without having to break the observable flow subscribing?

查看:91
本文介绍了如何在不中断可观察流订阅的情况下向主题发送不同的可观察结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用简洁的示例编辑了问题.我认为这将使人们更容易理解.请注意,这个示例是超级简化的,通常我在不同组件之间分层放置,但是对于这个问题就足够了.

Edited the question with a concise example. I think it'll make it easier for people to understand. Take note this example is super simplified, normally I layer things between different components, but for the question it will suffice.

使用此组件.它使用获取的对象的名称,以及获取下一个对象的按钮.为了获得下一个REST请求的值,除了订阅答案外,我别无其他方法,而我想要的是拥有类似"combineLatest"的内容.但为了未来",我可以合并最新的流.

Take this component. It takes the name of a fetched object, and a button to fetch the next object. To get the value of the next REST request, I know of no other way than to subscribe to the answer, and what I would like is to have something like "combineLatest" but for "the future", so I can combineLatest of later streams.

import { Component, VERSION, OnInit } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  
    private readonly PEOPLE_API_ENDPOINT = `https://swapi.dev/api/people/`;

   private characterSubject : BehaviorSubject<any> = new BehaviorSubject<any>({name: 'loading'});
  private currentCharacter: number = 1;
  
  character$ : Observable<any> = this.characterSubject.asObservable();
  
  constructor(
    private http: HttpClient
  ) {}
    
  ngOnInit() {
    this.updateCurrentCharacter();
  }

  nextCharacter() : void {
    this.currentCharacter ++;
    this.updateCurrentCharacter();
  }

  //I would want to avoid subscribing, instead
  //I would like some sort of operation to send the stream
  //emissions to the subject. As to not break the observable
  //chain up until presentation, like the best practices say.
  private updateCurrentCharacter() : void {
    this.fetchCharacter(this.currentCharacter)
      .subscribe( 
        character => this.characterSubject.next(character)
      );
  }

  private fetchCharacter (id: number) : Observable<any> {
        return this.http.get(this.PEOPLE_API_ENDPOINT + `${id}/`);
  }
}

<span>{{ character$ | async }} </span>

<button (click)="nextCharacter()">Next character</button>

在线演示

有没有办法做到这一点?做类似"emitIn(characterSubject)"的事情.我认为没有什么比这更像动态地向源中添加源排放了.

Is there any way to do that? Doing something like "emitIn(characterSubject)". I think there is nothing like this, like dynamically add source emissions to a source.

推荐答案

如果我理解正确,则您有一项服务,该服务具有一些触发http调用的方法,例如 dataRepository.fetch(id),并且您有不同的组件,需要在呼叫响应到达时做出反应.

If I understand right, you have a service which has some method that triggers an http call, like dataRepository.fetch(id), and you have different components that need to react when the response of the call arrives.

在这种情况下,有很多方法可以处理此类要求,一种方法是使用公开为服务公共属性的主题,这是我想知道的.

If this is the case, there are many ways to deal with such requirement, one being to use Subjects exposed as public properties of the service, which is what I understand you want to do.

要实现此行为,您所需要的代码就是您所需要的,换句话说,这是可以的

To achieve this behavior the code you have written is what you need, in other words this is OK

dataRepository.fetch(id)
  .subscribe(
    newData => currentData.next(newData)
  )

如果您想使其更完整并同时处理 error complete 情况,则可以这样编写

If you want to make it more complete and manage also the error and complete case, you may write it like this

dataRepository.fetch(id)
  .subscribe(currentData)

在最后一种形式中,您要传递 currentData 作为 subscribe 的Observer参数.虽然 currentData 也是可观察的,所以可以 next error complete .

In this last form, you are passing currentData as the Observer parameter of subscribe. currentDatathough is also an Observable and therefore can next, error and complete.

如果使用 ReplaySubject ,则可以添加存储最后结果的可能性,并将其显示在通知结果后创建的组件中.

If you use ReplaySubject you can add the possibility to store the last results and present them to components which are created after the notification of the result.

这篇关于如何在不中断可观察流订阅的情况下向主题发送不同的可观察结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆