java - Android Publish/Subscribe Singleton Example -


can provide simple example of using publish/subscribe singleton pattern pass information between fragments. last week asked passing data between fragments scenario below , method suggested; can't seem wrap head around it.

i have application using navigation drawer layout, various "sub applications" perform standalone functions (for example, calculators app, unrelated "sub apps" income tax calculations, metric/imperial conversions, etc). given calculator, i'd have data entry/selection fragment , data presentation fragment displays calculation in meaningful type of way. thus, activity in application mainactivity, holding navigation drawer , content pane. question is: best way design application such various calculators pass data data representation fragments, on click of button?

all examples in internet s...ks, uml diagrams absolutely unclear beginners , plenty of code experienced 1 can understand why using not that, 1 not another... so, let's construct moving step step , thinking logically.

first, need create kind of storage in singleton class - make data not depend on fragments' lifecycle. depending on purpose of app may different kinds of collections or primitives. add such fields singleton, example:

double conversionrate, taxrate; int securitynumber; .... // , on 

now need method of singleton update these data. let's call updatedata(). every time when data in of fragments changed user, fragment should invoke:

singleton.getinstance().updatedata(datatype, data); 

as arguments let's put type of data , object contains these data.

second, on every update need update data in other presentation fragments, right? updatedata() method should run through list of fragments running @ moment , send new data each. how implement it? -- easy, via callback method. that, need to:

1) create public interface kind of updateable 1 method: public void onupdate(int datatype, data data)

2) implement interface on every fragment implements updateable after class name

3) implement method onupdate() in class body. in implementation, each fragment consider, first, whether needs use data of given datatype, second, handle these received data (e. g. change textview value):

@override onupdate(int datatype, data data){    if (datatype == data_tax_rate){       textviewtaxrate.settext(string.parseint(data.getvalue()));    }  } 

third, how singleton know whom should send updated data? easy: add storage contain fragments updateable objects in it:

list<updateable> listeners = new arraylist<updateable>; 

and add 2 additional methods register , unregister objects (e. g. fragments) listeners. in first method should add listener mentioned list, in second remove it:

public void registerlistener(updateable listener){   if (!listeners.contains(listener)) {      listeners.add(listener);   } }  public void unregisterlistener(updateable listener){   if (listener != null && listeners.contains(listener)){      listeners.remove(listeners.indexof(listener));   } } 

now, each fragment wants receive updates (i. e. implements updateable interface) should register listener right after creation , resume:

singleton.getinstance().registerlistener(this); 

and unregister on ondestroy or when doesn't need listen updates anymore:

singleton.getinstance().unregisterlistener(this); 

n.b.: prevent memory leaks, should unregister listener when going not use object anymore. otherwise reference kept in listeners list making inaccessible garbage collector!

after created methods add , remove listeners, let's return singleton's method updatedata() mentioned before. main purpose store new data , send updates listeners, let's implement it:

public void updatedata(int datatype, data data){    // store new data    if (datatype == data_tax_rate){        this.taxrate = data.getvalue();    }     .....     // iterate through listeners , send updated data them    (updateable listener : listeners){        try {           listener.onupdate(datatype, data);        } catch (throwable e) {}    }  } 

now, every time user updates data in of fragments, or data updated calculation, call singleton.getinstance().updatedata(...) fragment -- new data stored in singleton , broadcasted other fragments automatically.

==================================================================

disclaimer: not exact implementation of observer design pattern, simplified version more clear , understandable beginners. that's why don't use common names such observer, notify etc. it's working example first step of understanding common design patterns more deeply.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -