How to convert an Observable into a BehaviorSubject?
This is how I convert my Observables to BehaviorSubjects:
import { Observable, BehaviorSubject } from 'rxjs';
export function convertObservableToBehaviorSubject<T>(observable: Observable<T>, initValue: T): BehaviorSubject<T> {
const subject = new BehaviorSubject(initValue);
observable.subscribe(subject);
return subject;
}
No need to convert it.
Just create a subject and attach observable to it with : obs.subscribe(sub)
example:
var obs = new rxjs.Observable((s) => {setTimeout(()=>{s.next([1])} , 500)}) //observable
var sub = new rxjs.BehaviorSubject([0]) //create subject
obs.subscribe(sub) //<----- HERE ----- attach observable to subject
setTimeout(() => {sub.next([2, 3])}, 1500) //subject updated
sub.subscribe(a => console.log(a)) //subscribe to subject
Note: obs.subscribe(sub)
is equivalent to :
obs.subscribe({
next: v => sub.next(v),
error: v => sub.error(v),
complete: () => sub.complete()
})
Run it online