Retrofit μ μ체μ μΌλ‘ λ°±κ·ΈλΌμ΄λμμ Thread Β λ₯Ό μ€ννκ³ Callback μ ν΅ν΄ λ©μΈ Thread μμ UI μ
λ°μ΄νΈκ° κ°λ₯νλ€.
μ΄ λ μ£Όλ‘ Call interface μ enqueue λ©μλλ₯Ό ν΅νμ¬ λΉλκΈ°μ μΌλ‘ API ν΅μ μ μ§ννκ³ , onResponse μ onFailue λ‘ ν΅μ κ²°κ³Όλ₯Ό λ°λλ€.
Rxjava μ Retrofit μ κ°μ΄ μ¬μ©ν κ²½μ°μλ λΉλκΈ° Thread λ₯Ό Rxjava μμ μ¬μ©νκΈ° λλ¬Έμ ꡬλ
μ ν΅ν΄ μ§ννλ€.
Rxjava μ Retrofit μ κ°μ΄ μ¬μ©νλ©΄ μΌκ΄λ λΉλκΈ° μμ
κ΄λ¦¬λ₯Ό ν μ μκ³ , 볡μ‘ν λΉλκΈ° μμ
μ λ³΄λ€ μ½κ² ꡬνν μ μλ€λ μ₯μ μ΄ μλ€. νμ§λ§, κ°λ¨ν μ΄ν리μΌμ΄μ
μΈ κ²½μ°μλ Rxjava λ₯Ό κ°μ΄ μ¬μ©ν νμλ μμΌλ―λ‘ κ°λ° μν©κ³Ό νλ‘μ νΈμ λ§κ² μ¬μ©νλ©΄ λλ€.
μλ μμ λ₯Ό ν΅ν΄ Rxjava μ Retrofit μ μ¬μ©νλ λ°©λ²μ μμ보μ.
dependencies {
...
implementation 'io.reactivex.rxjava3:rxandroid:3.0.2'
implementation 'io.reactivex.rxjava3:rxjava:3.1.5'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // JSON λ°μ΄ν° μ²λ¦¬λ₯Ό μν Gson 컨λ²ν°
implementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0' // RxJava 3 μ΄λν° μΆκ°
}
public class TestRequest {
private String name;
private String time;
public TestRequest (String name, String time) {
this.name = name;
this.time = time;
}
}
public interface TestApi {
@POST("/test")
Observable<ResponseBody> getTest(@Body NotificationRequest request);
@POST("/testSingle")
Single<String> getTestSingle();
}
// Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("μλ² URL")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build();
TestApi testApi = retrofit.create(TestApi.class);
// RxJava - Observable
testApi.getTest(request)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
// ꡬλ
μ μ²λ¦¬ν λ΄μ©
}
@Override
public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseBody responseBody) {
// κ²°κ³Ό λ°μ΄ν° μ²λ¦¬
}
@Override
public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
// μλ¬ μ²λ¦¬
}
@Override
public void onComplete() {
// μμ
μλ£ μ²λ¦¬
}
});
// Rxjava - Single
testApi.getTestSingle()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
// ꡬλ
μ μ²λ¦¬ν λ΄μ©
}
@Override
public void onSuccess(@NonNull String s) {
// μ±κ³΅
}
@Override
public void onError(@NonNull Throwable e) {
// μ€λ₯
}
});