java - Using RxJava and Okhttp -
i want request url using okhttp in thread (like io thread) , response
in android main thread, don't know how create observable
.
first add rxandroid
dependencies, create observable
this:
subscription subscription = observable.create(new observable.onsubscribe<response>() { okhttpclient client = new okhttpclient(); @override public void call(subscriber<? super response> subscriber) { try { response response = client.newcall(new request.builder().url("your url").build()).execute(); if (response.issuccessful()) { if(!subscriber.isunsubscribed()){ subscriber.onnext(response); } subscriber.oncompleted(); } else if (!response.issuccessful() && !subscriber.isunsubscribed()) { subscriber.onerror(new exception("error")); } } catch (ioexception e) { if (!subscriber.isunsubscribed()) { subscriber.onerror(e); } } } }) .subscribeon(schedulers.io()) .observeon(androidschedulers.mainthread()) .subscribe(new subscriber<response>() { @override public void oncompleted() { } @override public void onerror(throwable e) { } @override public void onnext(response response) { } });
it request url in thread (io thread) , observe on android main thread.
and when leave screen use subsribtion.unsubscribe()
avoid memory leak.
when use observable.create
, should write lot of boilerplate code, must handle subscription own. better alternative use defer. form doc:
do not create observable until observer subscribes, , create fresh observable each observer
the defer operator waits until observer subscribes it, , generates observable, typically observable factory function. afresh each subscriber, although each subscriber may think subscribing same observable, in fact each subscriber gets own individual sequence.
so marcin koziĆski mentioned, need this:
final okhttpclient client = new okhttpclient(); observable.defer(new func0<observable<response>>() { @override public observable<response> call() { try { response response = client.newcall(new request.builder().url("your url").build()).execute(); return observable.just(response); } catch (ioexception e) { return observable.error(e); } } });
Comments
Post a Comment