BVtp
BVtp

Reputation: 2480

Implementing a universal Observer Pattern/Listener for the app

In my android app there's a lot of updates that need to be done after the lifecycle has been started and passed the initial states. Right now I was working on adding an option to allow the user to disable receiving push notifications , and I had to create a custom "listener" so it would reach a method that's inside an onCreate callback, and I've noticed it is not the first time I'm doing this. So I was wondering, is there a way to make some "abstract" interface, instead of implementing a new listener for each class (there are dozens of them...).

Just for the sake of making myself more clear , here's a pseudo-code of what I mean:

interface X:
{
   void onDoneFragment1();
   void onDoneFragment2();
   void onDoneFragment3();
...
}

and then

fragment 1:
..
x.setOnListenFragment1( new OnDoneFragment1(){
@Override
public onDoneFragment1(){
......
..

same for fragment 2 and others..

 fragment 2:
    ..
    x.setOnListenFragment2( new OnDoneFragment2(){
    @Override
    public onDoneFragment2(){
    ......
    ..

Upvotes: 3

Views: 480

Answers (1)

mawalker
mawalker

Reputation: 2070

Yes, you have two options:

1) Just make an abstract class with all blank impl. methods that way

2) If you use RetroLambda to add Java8 syntax support to Java7, and by relation to Android.... You can make an Interface with 'default' methods.

Abstract class:

abstract class X:
{
   // having this makes sure the person only uses a method they have 'overridden'
   private Exception makeException(){
        return new Exception("Called Method from abstract class that wasn't overridden");
   }
   void onDoneFragment1(){throw makeException();}
   void onDoneFragment2(){throw makeException();}
   void onDoneFragment3(){throw makeException();}
...
}

Interface with 'default methods'

interface X:
{
   // having this makes sure the person only uses a method they have 'overridden'
   private Exception makeException(){
        return new Exception("Called Method from abstract class that wasn't overridden");
   }
   default void onDoneFragment1(){throw makeException();}
   default void onDoneFragment2(){throw makeException();}
   default void onDoneFragment3(){throw makeException();}
...
}

Upvotes: 1

Related Questions