How to convert an Observable into a BehaviorSubject?












0















I'm trying to convert an Observable into a BehaviorSubject. Like this:



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


I have also tried:



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


And:



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


And:



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


But none of these works. For now I have to implement like this:



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


This would be a little bit ugly in a class:



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

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


So, is there a simpler way to convert a Observable to a BehaviorSubject without using class constructor?





This is my real case:



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`
}
}









share|improve this question




















  • 1





    What is the usecase for this? You can typically use just merge. Using subscribe is the most Rx way I think.

    – martin
    Nov 19 '18 at 10:00











  • Which is the reason you want to convert an Observable to a BehaviourSubject? Is it because you want to have access to the last value? If this is the case you can look at shareReply or a sequence of publishReplay and refCount

    – Picci
    Nov 19 '18 at 10:08











  • @Picci Yes. I want to have access to the latest value. Thanks for advise! I'm going to have a look on these APIs.

    – awmleer
    Nov 19 '18 at 10:11











  • @Picci Actually I want to write something like b$.value or b$.getValue().

    – awmleer
    Nov 19 '18 at 10:16






  • 1





    With subjects, value and getValue are code smells and are best avoided.

    – cartant
    Nov 19 '18 at 13:01


















0















I'm trying to convert an Observable into a BehaviorSubject. Like this:



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


I have also tried:



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


And:



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


And:



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


But none of these works. For now I have to implement like this:



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


This would be a little bit ugly in a class:



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

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


So, is there a simpler way to convert a Observable to a BehaviorSubject without using class constructor?





This is my real case:



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`
}
}









share|improve this question




















  • 1





    What is the usecase for this? You can typically use just merge. Using subscribe is the most Rx way I think.

    – martin
    Nov 19 '18 at 10:00











  • Which is the reason you want to convert an Observable to a BehaviourSubject? Is it because you want to have access to the last value? If this is the case you can look at shareReply or a sequence of publishReplay and refCount

    – Picci
    Nov 19 '18 at 10:08











  • @Picci Yes. I want to have access to the latest value. Thanks for advise! I'm going to have a look on these APIs.

    – awmleer
    Nov 19 '18 at 10:11











  • @Picci Actually I want to write something like b$.value or b$.getValue().

    – awmleer
    Nov 19 '18 at 10:16






  • 1





    With subjects, value and getValue are code smells and are best avoided.

    – cartant
    Nov 19 '18 at 13:01
















0












0








0








I'm trying to convert an Observable into a BehaviorSubject. Like this:



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


I have also tried:



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


And:



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


And:



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


But none of these works. For now I have to implement like this:



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


This would be a little bit ugly in a class:



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

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


So, is there a simpler way to convert a Observable to a BehaviorSubject without using class constructor?





This is my real case:



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`
}
}









share|improve this question
















I'm trying to convert an Observable into a BehaviorSubject. Like this:



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


I have also tried:



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


And:



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


And:



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


But none of these works. For now I have to implement like this:



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


This would be a little bit ugly in a class:



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

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


So, is there a simpler way to convert a Observable to a BehaviorSubject without using class constructor?





This is my real case:



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`
}
}






javascript typescript rxjs observable behaviorsubject






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 '18 at 10:16







awmleer

















asked Nov 19 '18 at 9:57









awmleerawmleer

4572515




4572515








  • 1





    What is the usecase for this? You can typically use just merge. Using subscribe is the most Rx way I think.

    – martin
    Nov 19 '18 at 10:00











  • Which is the reason you want to convert an Observable to a BehaviourSubject? Is it because you want to have access to the last value? If this is the case you can look at shareReply or a sequence of publishReplay and refCount

    – Picci
    Nov 19 '18 at 10:08











  • @Picci Yes. I want to have access to the latest value. Thanks for advise! I'm going to have a look on these APIs.

    – awmleer
    Nov 19 '18 at 10:11











  • @Picci Actually I want to write something like b$.value or b$.getValue().

    – awmleer
    Nov 19 '18 at 10:16






  • 1





    With subjects, value and getValue are code smells and are best avoided.

    – cartant
    Nov 19 '18 at 13:01
















  • 1





    What is the usecase for this? You can typically use just merge. Using subscribe is the most Rx way I think.

    – martin
    Nov 19 '18 at 10:00











  • Which is the reason you want to convert an Observable to a BehaviourSubject? Is it because you want to have access to the last value? If this is the case you can look at shareReply or a sequence of publishReplay and refCount

    – Picci
    Nov 19 '18 at 10:08











  • @Picci Yes. I want to have access to the latest value. Thanks for advise! I'm going to have a look on these APIs.

    – awmleer
    Nov 19 '18 at 10:11











  • @Picci Actually I want to write something like b$.value or b$.getValue().

    – awmleer
    Nov 19 '18 at 10:16






  • 1





    With subjects, value and getValue are code smells and are best avoided.

    – cartant
    Nov 19 '18 at 13:01










1




1





What is the usecase for this? You can typically use just merge. Using subscribe is the most Rx way I think.

– martin
Nov 19 '18 at 10:00





What is the usecase for this? You can typically use just merge. Using subscribe is the most Rx way I think.

– martin
Nov 19 '18 at 10:00













Which is the reason you want to convert an Observable to a BehaviourSubject? Is it because you want to have access to the last value? If this is the case you can look at shareReply or a sequence of publishReplay and refCount

– Picci
Nov 19 '18 at 10:08





Which is the reason you want to convert an Observable to a BehaviourSubject? Is it because you want to have access to the last value? If this is the case you can look at shareReply or a sequence of publishReplay and refCount

– Picci
Nov 19 '18 at 10:08













@Picci Yes. I want to have access to the latest value. Thanks for advise! I'm going to have a look on these APIs.

– awmleer
Nov 19 '18 at 10:11





@Picci Yes. I want to have access to the latest value. Thanks for advise! I'm going to have a look on these APIs.

– awmleer
Nov 19 '18 at 10:11













@Picci Actually I want to write something like b$.value or b$.getValue().

– awmleer
Nov 19 '18 at 10:16





@Picci Actually I want to write something like b$.value or b$.getValue().

– awmleer
Nov 19 '18 at 10:16




1




1





With subjects, value and getValue are code smells and are best avoided.

– cartant
Nov 19 '18 at 13:01







With subjects, value and getValue are code smells and are best avoided.

– cartant
Nov 19 '18 at 13:01














2 Answers
2






active

oldest

votes


















0














I have pretty concerns about the use case too. But here it comes a solution, feel free vote down as long you leave feedback too. Since BehaviourSubject and any other Subject are Observables,



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);





share|improve this answer





















  • 1





    Thanks for answering! But bs is still an observable and bs.value is undefined.😥

    – awmleer
    Nov 22 '18 at 12:14



















0














This is how I convert my Observables to BehaviorSubjects:



import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

export function convertObservableToBehaviorSubject<T>(observable: Observable<T>, initValue: T): BehaviorSubject<T> {
const subject = new BehaviorSubject(initValue);

observable.subscribe(
(x: T) => {
subject.next(x);
},
(err: any) => {
subject.error(err);
},
() => {
subject.complete();
},
);

return subject;
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372138%2fhow-to-convert-an-observable-into-a-behaviorsubject%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I have pretty concerns about the use case too. But here it comes a solution, feel free vote down as long you leave feedback too. Since BehaviourSubject and any other Subject are Observables,



    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);





    share|improve this answer





















    • 1





      Thanks for answering! But bs is still an observable and bs.value is undefined.😥

      – awmleer
      Nov 22 '18 at 12:14
















    0














    I have pretty concerns about the use case too. But here it comes a solution, feel free vote down as long you leave feedback too. Since BehaviourSubject and any other Subject are Observables,



    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);





    share|improve this answer





















    • 1





      Thanks for answering! But bs is still an observable and bs.value is undefined.😥

      – awmleer
      Nov 22 '18 at 12:14














    0












    0








    0







    I have pretty concerns about the use case too. But here it comes a solution, feel free vote down as long you leave feedback too. Since BehaviourSubject and any other Subject are Observables,



    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);





    share|improve this answer















    I have pretty concerns about the use case too. But here it comes a solution, feel free vote down as long you leave feedback too. Since BehaviourSubject and any other Subject are Observables,



    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);






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 22 '18 at 12:39









    awmleer

    4572515




    4572515










    answered Nov 20 '18 at 5:07









    LuillyfeLuillyfe

    1,94432332




    1,94432332








    • 1





      Thanks for answering! But bs is still an observable and bs.value is undefined.😥

      – awmleer
      Nov 22 '18 at 12:14














    • 1





      Thanks for answering! But bs is still an observable and bs.value is undefined.😥

      – awmleer
      Nov 22 '18 at 12:14








    1




    1





    Thanks for answering! But bs is still an observable and bs.value is undefined.😥

    – awmleer
    Nov 22 '18 at 12:14





    Thanks for answering! But bs is still an observable and bs.value is undefined.😥

    – awmleer
    Nov 22 '18 at 12:14













    0














    This is how I convert my Observables to BehaviorSubjects:



    import { Observable } from 'rxjs/Observable';
    import { BehaviorSubject } from 'rxjs/BehaviorSubject';

    export function convertObservableToBehaviorSubject<T>(observable: Observable<T>, initValue: T): BehaviorSubject<T> {
    const subject = new BehaviorSubject(initValue);

    observable.subscribe(
    (x: T) => {
    subject.next(x);
    },
    (err: any) => {
    subject.error(err);
    },
    () => {
    subject.complete();
    },
    );

    return subject;
    }





    share|improve this answer




























      0














      This is how I convert my Observables to BehaviorSubjects:



      import { Observable } from 'rxjs/Observable';
      import { BehaviorSubject } from 'rxjs/BehaviorSubject';

      export function convertObservableToBehaviorSubject<T>(observable: Observable<T>, initValue: T): BehaviorSubject<T> {
      const subject = new BehaviorSubject(initValue);

      observable.subscribe(
      (x: T) => {
      subject.next(x);
      },
      (err: any) => {
      subject.error(err);
      },
      () => {
      subject.complete();
      },
      );

      return subject;
      }





      share|improve this answer


























        0












        0








        0







        This is how I convert my Observables to BehaviorSubjects:



        import { Observable } from 'rxjs/Observable';
        import { BehaviorSubject } from 'rxjs/BehaviorSubject';

        export function convertObservableToBehaviorSubject<T>(observable: Observable<T>, initValue: T): BehaviorSubject<T> {
        const subject = new BehaviorSubject(initValue);

        observable.subscribe(
        (x: T) => {
        subject.next(x);
        },
        (err: any) => {
        subject.error(err);
        },
        () => {
        subject.complete();
        },
        );

        return subject;
        }





        share|improve this answer













        This is how I convert my Observables to BehaviorSubjects:



        import { Observable } from 'rxjs/Observable';
        import { BehaviorSubject } from 'rxjs/BehaviorSubject';

        export function convertObservableToBehaviorSubject<T>(observable: Observable<T>, initValue: T): BehaviorSubject<T> {
        const subject = new BehaviorSubject(initValue);

        observable.subscribe(
        (x: T) => {
        subject.next(x);
        },
        (err: any) => {
        subject.error(err);
        },
        () => {
        subject.complete();
        },
        );

        return subject;
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 24 at 17:15









        tmueckschtmuecksch

        2,52532446




        2,52532446






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372138%2fhow-to-convert-an-observable-into-a-behaviorsubject%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud

            Zucchini