alitaleg
alitaleg

Reputation: 165

How to obtain string out of IObservable<string> Reactive Extensions

I have a method that returns IObservable

private IObservable<String> Name() {}

I want to obtain a regular string after calling that method such as

string name = Name(). ???

What do I use instead of the ???

Upvotes: 0

Views: 1553

Answers (3)

Ana Betts
Ana Betts

Reputation: 74654

How about:

string name = await Name();

Or:

string name = Name.First();

If you're into the whole synchronicity thing.

Upvotes: 0

cwharris
cwharris

Reputation: 18125

There's a few of ways to do this.

First, you could just Wait, as James suggested. However, this has the potential of entering a dead-lock, depending on the implementation of the Name observable and the environment in which you are running your code.

string name = Name().Wait();

Or, you could set it as a side-effect of your subscription. This is better, but it begs the questions, "What if I need it synchronously?"

string name = null;
Name().Subscribe(x => name = x);

If you have access to the TPL, you also have some options with async.

public async Task DoThing() {
    string name = await Name(); // or await Name().FirstOrDefaultAsync();
};

So, if you need to synchronize to a non-reactively, you could use the TPL and async / await. If you need to perform a side-effect which uses the name, you could use Do or Subscribe, and if you understand how Wait works, you could retrieve the name in a purely synchronous environment.

To understand which is best for you, I think we'd all need to see a bit more code. Basically, how are you going to use the name? That's extremely important to understanding how you should use the observable.

Upvotes: 1

James World
James World

Reputation: 29776

string name = Name().Wait();

... which will block. Not really in the spirit of Rx though. It's better to Subscribe to it with a delegate that will be called when the result is available:

Name().Subscribe(name => /* Do something with name */);

Upvotes: 4

Related Questions