简体   繁体   English

如何从 Observable 中获取最后一个值?

[英]how can i get last value from a Observable?

i try to get last value from a observable.我试图从可观察到的最后一个值。 the example code is示例代码是

// RxJS v6+
import { lastValueFrom, Subject } from 'rxjs';
import { scan } from 'rxjs/operators';

async function main() {
  const subject = new Subject();

  const example = subject.pipe(
    scan((acc, curr) => {
      return Object.assign({}, acc, curr);
    }, {}),
  );
  const subscribe = example.subscribe((val) =>
    console.log('Accumulated object:', val),
  );
  subject.next({ name: 'Joe' });
  subject.next({ age: 30 });
  subject.next({ favoriteLanguage: 'JavaScript' });

  console.log('+++++++++++++');
  const resp = await lastValueFrom(example);
  console.log(resp);
  console.log('end');
}

main()
  .catch((e) => {
    console.error(e);
  })
  .finally(async () => {
    console.log('final');
  });

the output is输出是

➜  npns-service git:(mr/master/658) ✗ ts-node prisma/test.ts
Accumulated object: { name: 'Joe' }
Accumulated object: { name: 'Joe', age: 30 }
Accumulated object: { name: 'Joe', age: 30, favoriteLanguage: 'JavaScript' }
+++++++++++++

i can't got the resp output message.我无法得到相应的输出消息。

how can i got the resp value from example Observable?我如何从示例 Observable 中获得 resp 值?

Update your code to complete your observable:更新您的代码以完成您的 observable:

setTimeout(() => { // setTimeout is just a simple way to use JS's event loop
    subject.next({ name: 'Joe' });
    subject.next({ age: 30 });
    subject.next({ favoriteLanguage: 'JavaScript' });
    subject.complete(); // signal that our observable is done emitting
    // subject.next(something) here would do 
    // nothing, the observable is complete 
}, 0);

console.log('+++++++++++++');
const resp = await lastValueFrom(example);
console.log(resp);
console.log('end');


If you don't complete an observable, as far as your run-time is aware it may still emit something else in a minute, 5 hours, next year - who knows?如果你没有完成一个 observable,就你的运行时所知,它可能仍会在一分钟、5 小时、明年发出其他东西——谁知道呢? There must be some condition that triggers completion.必须有一些条件触发完成。

A quick aside: I threw the code that emits on your subject into the event loop so that the code that follows can await it.顺便说一句:我将在您的主题上发出的代码放入事件循环中,以便后面的代码可以await它。 Otherwise your subject would complete synchronously before that code was ever run.否则,您的主题将在该代码运行之前同步完成。

Update 1: how can i got a newest value from a observable?更新 1:如何从 observable 中获得最新值?

Make example an observable that remembers (buffers) the last emission.example作为一个可观察的对象,它可以记住(缓冲)最后一次发射。 Then just use take(1) to read the buffered value.然后只需使用take(1)读取缓冲值。

const subject = new Subject();

const example = subject.pipe(
    scan((acc, curr) => Object.assign({}, acc, curr), {}),
    shareReplay(1)
);
example.subscribe(val =>
    console.log('Accumulated object:', val)
);

subject.next({ name: 'Joe' });
subject.next({ age: 30 });
subject.next({ favoriteLanguage: 'JavaScript' });

console.log('+++++++++++++');
const resp = await lastValueFrom(example.pipe(take(1));
console.log(resp);
console.log('end');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM