i start development on android app. interested in using otto or eventbus in app assist making asynchronous rest network calls , notifying main thread when calls have returned.the 1 major flaw use of these busses have found during research there typically many event classes have created. there patterns or approaches reduce number of event classes have used?
the concept
the best way have solved issue of many event classes using static nested classes can read more them here.
now using above concept here how solve problem:
so suppose have class called doctor using create object passing around application. want send same object on network , retrieve json in context of same object , feed subscriber with. create 2 classes
- doctorjsonobject.java contains information returned json data ,
- doctorobject.java has data passing around in app.
you don't need that. instead this:
public class doctor{ static class jsondata{ string name; string ward; string id; //add getters , setter } static class appdata{ public appdata(string username, string password){ //do within constructor } string username; string password; //add getters , setters } } now have 1 doctors class encapsulates both events post network , post network.
doctor.jsondata represents data returned network in json format.
doctor.appdata represents "model" data being passed around in app.
to use class' appdata object post event:
/* post data fragment fetch data server. data being posted within app lets packaged doctor object doctors username , password. */ public function postrequest(){ bus.post(new doctor.appdata("doctors_username","doctros_password")); } the subscriber within implementation listens object , makes http request , returns doctor.jsondata:
/* retrofit implementation containing listener doctor's post */ @subscribe public void doctorslogin(doctor.appdata doc){ //put doctor.jsonobject in callback api.getdoctor(doc.getdoctorsname(), doc.getpassword(), new callback<doctor.jsonobject>() { @override public void success(doctor.jsonobject doc, response response) { bus.post(doc); } @override public void failure(retrofiterror e) { //handle error } }); } } with above implementation have encapsulated doctor object related events within one doctor class , accessed different types of objects need @ different times using static inner classes. less classes more structure.
Comments
Post a Comment