Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing C#-like events in Android/Java

I'm used to programming in C#, and one thing I miss about Java is that it doesn't seem to have C#'s nice built-in event handling capabilities:

// define event signature
public delegate void SomeEventHandler();

class SomeEventGenerator {
    // define subscribable event property
    public event SomeEventHandler SomeEvent;

    protected void OnSomeEvent() {
        if (SomeEvent != null) {
            SomeEvent();
        }
    }
}

class SomeEventClient {
    public SomeEventClient(SomeEventGenerator eg) {
        // subscribe
        eg.SomeEvent += new SomeEventHandler(eg_SomeEvent);
        // do some stuff
        // unsubscribe
        eg.SomeEvent -= new SomeEventHandler(eg_SomeEvent);
    }

    private void eg_SomeEvent() {
        // handle event
    }
}

What's the best way to get something similar and lightweight in Java/Android which has the ability to subscribe/unsubscribe multiple event clients and call all subscribed clients at once?

like image 844
We Are All Monica Avatar asked Jan 17 '11 11:01

We Are All Monica


1 Answers

You would want to look into the concept of listeners in java. I found a very good article called "C# from a Java developers perspective" that you might want to check out.

http://www.25hoursaday.com/CsharpVsJava.html

like image 145
Christian Resma Helle Avatar answered Sep 21 '22 06:09

Christian Resma Helle