retrofit2 abstraction network android -
i use retrofit2 handle network of android app. want abstract network, networkmanager.getsearch()
, async request , ui update. tutoriels i've seen have, code update ui in callback on @override onresponse
in code of activity update ui (and want handle in networkmanager). wanted pass function or method handle return of callback research think it's not impossible. missing on use of retrofit2 ? did have ideas solve problem or how abstraction of network in android ?
it's not impossible, although differs depending on whether use synchronous (execute()
) or asynchronous (enqueue()
) call.
as know here, how handle them:
call<list<car>> carscall = carinterface.loadcars(); try { response<list<car>> carsresponse = carscall.execute(); } catch (ioexception e) { e.printstacktrace(); //network exception thrown here } if(carsresponse != null && !carsresponse.issuccess() && carsreponse.errorbody() != null){ // handle carsresponse.errorbody() }
for async calls:
call<list<car>> call = service.loadcars(); call.enqueue(new callback<list<car>>() { @override public void onresponse(response<list<car>> response) { // result response.body(), headers, status codes, etc } @override public void onfailure(throwable t) { //handle error } });
for service defined so
public interface retrofitcarservice { @get("api/getcars") call<list<car>> getcars(); }
but if you'd want abstract it, this
public interface yourcallback<t> { void onsuccess(t t); void onerror(throwable throwable); } public interface carservice { void getcars(yourcallback<list<car>> callback); } public class carserviceimpl implements carservice { private retrofitcarservice retrofitcarservice; public carserviceimpl(retrofitcarservice retrofitcarservice) { this.retrofitcarservice = retrofitcarservice; } public void getcars(yourcallback<list<car>> callback) { retrofitcarservice.getcars().enqueue(new callback<list<car>>() { @override public void onresponse(response<list<car>> response) { callback.onsuccess(response.body()); } @override public void onfailure(throwable t) { callback.onerror(t); } } } }
and you'd abstracted away:
@inject carservice carservice; public void something() { carservice.getcars(new yourcallback<list<car>>() { public void onsuccess(list<car> cars) { refreshdataset(cars); } public void onerror(throwable throwable) { showerror(throwable); } }); }
please note force service
async, throws away ability of call
s represent both sync , async operations. if think bit, can abstract away call<t>
.
Comments
Post a Comment