简体   繁体   中英

Rx .NET what is the right way to observe a function call

I'm learning to do rx in .NET the right way and wondering what is the usual way to make an observable stream out of a remote function call.

At the moment, I just create a Subject<T> and call its OnNext function within the callback method.

Example:

subject.AsObservable().Where(...).Subscribe(...);

This is where I filter and subscribe to the observable.

await speechService.StartListeningAsync(f => OnSpeechCommandRecognized(f), 
                  cts.Token, OnError, interimResults).ConfigureAwait(false);

This is where I pass the callback method to the speech service.

private void OnSpeechCommandRecognized(StreamingRecognitionResult result)
{
    subject.OnNext(result);
}

This is where I call the OnNext function within the callback method.

Another way I was looking at was to call Observable.Start and subscribe to the returning observable, but I don't think this is the way to go.

Also i could wrap the call around an Observable.Create .

So my question is: Is this example the right way to subscribe to a method emitting results?

What if you used Create rather than a Subject ?

Since your API returns a task which presumably won't complete until it's time to stop listening, you can use FromAsync to wrap that call and then create a closure to the Create 's observer. Subscribe to the inner observable, and you have an observable which, when subscribed to, will yield results from the StartListeningAsync callback until the associated task completes (or errors).

Observable.Create((observer, outerCancel) =>
    Observable.FromAsync(innerCancel =>
            speechService.StartListeningAsync(
                observer.OnNext,
                innerCancel,
                observer.OnError,
                interimResults
            ))
        .Subscribe(observer, outerCancel)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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