'How to return Observable from Callback

I have a service in which I want to implement the logic of an SDK. From this SDK I want to call an event that returns a payload.
I want to create a method in which the event is called and wrap it in an Observable to be able to subscribe to the response of the event. I as well created an interface in order to assure type-safety of the sdk's response.

This is what has been created so far:

export interface SdkPayload{
     avatar,
     name,
     jobTitle,
     availability
    }

export class TestService {
    sdk:someSDK;
    

     //method that returns an Observable
    getPayload$(): Observable<SdkPayload[]> {

//create new Observable of type defined in Interface return new Observable<SdkPayload[]>((subscriber) => { const callbackFunction = (sdkPayload:SdkPayload[]) => {

                    this.someSDK.on('connected', (payload) => {
                      
                        payload.greeting.agent.avatar,
                        payload.greeting.agent.name,
                        payload.greeting.agent.jobTitle,
                        payload.availability;
                    });
                    
                    subscriber.next(sdkPayload);
                };
                this.customerSDK.on('connected', callbackFunction);
                return () => {
                    this.customerSDK('off', callbackFunction);
                };
            });
        }

Component:

    export class AppComponent{
       payloadResults$: Observable<SdkPayload[]>;
    
    constructor (private service:TestService){}
    
    callMethod(){
     this.payloadResults$=this.service.getPayload$();
    }
}

I have the feeling that the event that I use from the sdk is not correctly implemented or correctly wrapped in the Observable. In the end my goal is to wrap the SDK Response into an Observable, so that I can subscribe to its response.



Solution 1:[1]

You could create a subject. On Service Class init a subject:

  sdkPayloadSubject = new Subject<SdkPayload[]>();
 // transfor subject to an observable
    payloadResults$: Observable<SdkPayload[]> = this.sdkPayloadSubject.asObservable();
//add method accept each triggered sdk value
newLoadedSdkValue(newSdkPayload:SdkPayload[]){
this.sdkPayloadSubject.next(newSdkPayload);
}

On your getPayload function You could use above function to trigger the new value as observable instead of:

subscriber.next(sdkPayload);

use

this.newLoadedSdkValue(sdkPayload);

Then on your component class you could use the new observable format

    constructor (private service:TestService){
this.payloadResults$ = this.service.payloadResults$

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zrelli Majdi