Mynca
Mynca

Reputation: 21

Combine dependent IObservables

I'm having trouble to combine two Observables which are dependent (meaning the result of one sequence is needed as input for the other).

I have 2 methods:

For every message returned by method 1 I have to execute method 2 and add the result to the Message object.

I know there are methods like CombineLatest, Zip, etc... . But it seems to me that all these methods combine sequences which are not dependent (meaning the result of one sequence is not needed to be able to execute the second sequence).

Is this possible with IObservables? Could someone give me a start on how to tackle this?

Upvotes: 2

Views: 69

Answers (1)

Enigmativity
Enigmativity

Reputation: 117175

So, if I've understood, your signatures look like this:

IObservable<List<Message>> Method1()

IObservable<ExtraInfoOfMessage> Method2(Message parameter)

And, your message looks like this:

public class Message
{
    public ExtraInfoOfMessage ExtraInfoOfMessage { get; set; }
}

Then you can do this:

Func<Message, ExtraInfoOfMessage, Message> combine = (m, e) =>
{
    m.ExtraInfoOfMessage = e;
    return m;
};

IObservable<Message> query =
    from messages in Method1()
    from message in messages
    from extra in Method2(message)
    select combine(message, extra);

If you want your query to return a list of messages then do this:

IObservable<IList<Message>> query =
(
    from messages in Method1()
    from message in messages
    from extra in Method2(message)
    select combine(message, extra)
).ToList();

Upvotes: 1

Related Questions