mercredi 17 février 2016

Callback-way to work with Events

I do not understand some things of work with callbacks.

I have some third-party code wich connect,disconnect,subscribe to values from some system.

So, the example is:

class Subscriber:ISubscriber
{
  public void OnConnected()
  {

  }

 public void OnDisconnected()
  {

  }
}

Then, it uses:

var subscriber=new Subscriber();
_someSystemObj.CreateConnection(subscriber); //i do not understand how it works there

And then _someSystemObj calls OnConnected or OnDisconnected.

So, i have two questions: 1.How can _someSystemObj calls OnConnected method (it use Observer pattern or may be it use it other way. Can you describe it? Get some schematic code to understand how it may work.

  1. If i want to do many steps when OnDisconnect happens: should i throw some public event to other classes? I mean than i can not do Disconnection in this OnDisconnect method (i have to do some steps in other part of my code and at old version of this API i just rethrow event OnDisconnect on top of my program and then handle it.)

This old version of code looks like:

_server.OnDisconnect+=OnDisconnectHandler;

void OnDisconnectHandler(..)
{
 if(OnReconnect!=null)//some public event
   OnReconnect(e);// throw on top of my program and then handle it there
}

At new version of API i try to solve it by add public event and when OnDisconnect happens throw it on top:

class Subscriber:ISubscriber
{
  public event EventHandler<EventArgs> OnDisconnectedHappens;

  public void OnConnected()
   {

   }

public void OnDisconnected()
  {
        if(OnDisconnectedHappens!=null)
           OnDisconnectedHappens(this,e);//thow on top
  }
}

And in some place:

   _subscriber.OnDisconnectHappens+=OnDisconnectHandler; //and do my work

Or, may be it not right way. May be i should do something else?

Please,can you give me a some link, that i can learn about this model of event callbacks? Or, may be i do it correctly?

Aucun commentaire:

Enregistrer un commentaire