Skip to content

Instantly share code, notes, and snippets.

@Evin1-
Last active December 10, 2021 14:59
Show Gist options
  • Save Evin1-/18ac094d5f40bf56dae357450d206ae8 to your computer and use it in GitHub Desktop.
Save Evin1-/18ac094d5f40bf56dae357450d206ae8 to your computer and use it in GitHub Desktop.
Migrate AsyncTask to RxJava
<uses-permission android:name="android.permission.INTERNET" />
dependencies {
// ...
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'com.squareup.okhttp3:okhttp:3.6.0'
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivityTAG_";
private static final String API_URL = "http://www.mocky.io/v2/57a01bec0f0000c10d0f650f";
private OkHttpClient client = new OkHttpClient();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
Log.d(TAG, "onSubscribe: " + d);
}
@Override
public void onNext(String value) {
Log.d(TAG, "onNext: " + value);
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "onError: ", e);
}
@Override
public void onComplete() {
Log.d(TAG, "onComplete: ");
}
});
}
private String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
private Observable<String> createObservable() {
//Could use fromCallable
return Observable.defer(new Callable<ObservableSource<? extends String>>() {
@Override
public ObservableSource<? extends String> call() throws Exception {
return Observable.just(run(API_URL));
}
});
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivityTAG_";
private static final String API_URL = "http://www.mocky.io/v2/57a01bec0f0000c10d0f650f";
private OkHttpClient client = new OkHttpClient();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
}
private String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
private class MyTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
try {
Log.d(TAG, "doInBackground: " + run(API_URL));
} 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