Created
February 2, 2016 02:16
-
-
Save vuhung3990/b23269be9ff8b262ed2e to your computer and use it in GitHub Desktop.
asynchronous in Rxjava
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// sample 2 asynchronous task | |
Observable<String> jsonTask = Observable.create(new Observable.OnSubscribe<String>() { | |
@Override | |
public void call(Subscriber<? super String> subscriber) { | |
subscriber.onNext(getJsonFromInternet()); | |
subscriber.onCompleted(); | |
} | |
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); | |
// SUBCRIBE | |
jsonTask.subscribe(new Subscriber<String>() { | |
@Override | |
public void onCompleted() { | |
Log.d(TAG, "onCompleted: "); | |
} | |
@Override | |
public void onError(Throwable e) { | |
Log.d(TAG, "onError: " + e.getMessage()); | |
} | |
@Override | |
public void onNext(String s) { | |
Log.d(TAG, "onNext: " + s); | |
} | |
}); | |
private String getJsonFromInternet() { | |
HttpURLConnection connection = null; | |
try { | |
URL url = new URL("http://api.androidhive.info/contacts/"); | |
connection = (HttpURLConnection) url.openConnection(); | |
connection.setRequestMethod("GET"); | |
connection.setConnectTimeout(5000); | |
connection.connect(); | |
// if(connection.getResponseCode() == 200){ | |
// | |
// } | |
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); | |
StringBuilder sb = new StringBuilder(); | |
String line; | |
while ((line = br.readLine()) != null) { | |
sb.append(line + "\n"); | |
} | |
br.close(); | |
return sb.toString(); | |
} catch (MalformedURLException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment