如何将一个Observable转换为BehaviorSubject?

时间:2018-11-19 09:57:24

标签: javascript typescript rxjs observable behaviorsubject

我正在尝试将Observable转换为BehaviorSubject。像这样:

a$ = new Observable()
b$ = BehaviorSubject.create(new BehaviorSubject(123), a$)
// 

我也尝试过:

a$ = new Observable()
b$ = new BehaviorSubject(a$, 123)
// 

并且:

a$ = new Observable()
b$ = a$.asBehaviorSubject(123)
// 

并且:

a$ = new Observable()
b$ = a$.pipe(
  toBehaviorSubject(123)
)
// 

但是这些都不起作用。现在,我必须像这样实现:

a$ = new Observable()
b$ = new BehaviorSubject(123)
a$.subscribe(b$)
// 

这在课堂上有点难看:

class Foo() {
  a$ = new Observable() // Actually, a$ is more complicated than this.
  b$ = new BehaviorSubject(123)

  constructor() {
    this.a$.subscribe(this.b$)
  }
}

那么,有没有更简单的方法可以在不使用类构造函数的情况下将Observable转换为BehaviorSubject?


这是我的真实情况:

export class Foo {
  autoCompleteItems$ = new BehaviorSubject<string[]>(null)
  autoCompleteSelected$ = new BehaviorSubject<number>(-1)
  autoCompleteSelectedChange$ = new Subject<'up'|'down'>()

  constructor() {
    this.autoCompleteItems$.pipe(
      switchMap((items) => {
        if (!items) return EMPTY
        return this.autoCompleteSelectedChange$.pipe(
          startWith('down'),
          scan<any, number>((acc, value) => {
            if (value === 'up') {
              if (acc <= 0) {
                return items.length - 1
              } else {
                return acc - 1
              }
            } else {
              if (acc >= items.length - 1) {
                return 0
              } else {
                return acc + 1
              }
            }
          }, -1)
        )
      })
    ).subscribe(this.autoCompleteSelected$)
  }

  doAutoComplete = () => {
    const item = this.autoCompleteItems$.value[this.autoCompleteSelected$.value]
    // do something with `item`
  }
}

3 个答案:

答案 0 :(得分:4)

无需转换。只需创建一个主题并对其进行观察即可。例如:

var obs = new rxjs.Observable((s) => {setTimeout(()=>{s.next([1])} , 500)}) //observable
var sub = new rxjs.BehaviorSubject([0]) //create subject
obs.subscribe(v => sub.next(v)) //attach observable to subject
setTimeout(() => {sub.next([2, 3])}, 1500) //subject updated
sub.subscribe(a => console.log(a)) //subscribe to subject

更新:您还可以附加错误处理程序并完成状态。在上面的示例中,可以使用:

代替obs.subscribe(v => sub.next(v))
obs.subscribe({
  next: v => sub.next(v),
  error: v => sub.error(v),
  complete: () => sub.complete()
})

答案 1 :(得分:0)

这是我将Observables转换为BehaviorSubjects的方式:

2018-12-01
2018-12-02
2018-11-03
2018-10-04

答案 2 :(得分:-1)

我也非常关注用例。但是这里提供了一个解决方案,只要您也留下反馈,就可以自由投票。由于BehaviourSubject和任何其他SubjectObservables

import { BehaviorSubject, from } from 'rxjs'; 
import { map, mergeMap } from 'rxjs/operators';


const source$ = from([1,2,3,4,5,6,7,8,9]);
const bs = new BehaviorSubject('start')
    .pipe(
        mergeMap(() => source$)
    );

bs.subscribe(console.log);