-2

I have a class RemoteData like below,

public class RemoteData
{
    public RemoteData(string Message, string IP)
    {
        this.IP = IP;
        this.Message = Message;
    }

    public string IP;
    public string Message;
}

Now I have a IObservable<T> method UdpStream like below,

 public static IObservable<RemoteData> UdpStream(IPEndPoint endpoint, Func<string, RemoteData> processor)
    {
        return Observable.Using(() => new UdpClient(endpoint),
            udpClient => Observable.Defer(() => 
                udpClient.ReceiveAsync().ToObservable()).Repeat().Select(result => processor(Encoding.UTF8.GetString(result.Buffer))));
    }

Now how to call UdpStream, how to pass Func parameter?

var stream = UdpStream(new IPEndPoint(IPAddress.Any, 514), 2nd Param);
SpruceMoose
  • 9,737
  • 4
  • 39
  • 53
user584018
  • 10,186
  • 15
  • 74
  • 160
  • 1
    read thru all of the answers here and you will understand - https://stackoverflow.com/questions/878650/explanation-of-func – MethodMan Dec 03 '17 at 14:47

1 Answers1

2

Func<T, U> represents a delegate that takes a T parameter and returns U. You can initialize a Func<T, U> using a method reference that matches that signature, or using a lambda expression.

Using a Func<,> as parameter is a common idiom for a callback. For example, if you have a method similar to this:

public static void Method(Func<T, U> func)
{
     // ...
}

We can expect that Method will call whaterver you pass in the func parameter. In fact, this happens in the code your present (the parameter Func<string, RemoteData> processor is called where it says processor(Encoding.UTF8.GetString(result.Buffer))).


Now, you have Func<string, RemoteData>, thus you need a method that takes string and returns RemoteData. For example:

public static RemoteData Example(string input)
{
    // ...
}

// ...

var observable = UdpStream(endpoint, Example);
Theraot
  • 31,890
  • 5
  • 57
  • 86