खोज…


RxJava के साथ रेट्रोफिट 2

सबसे पहले, build.gradle फ़ाइल में प्रासंगिक निर्भरताएँ जोड़ें।

dependencies {
    ....
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    ....
}

फिर वह मॉडल बनाएं जिसे आप प्राप्त करना चाहते हैं:

public class Server {
    public String name;
    public String url;
    public String apikey;
    public List<Site> siteList;
}

दूरस्थ सर्वर के साथ डेटा का आदान-प्रदान करने के लिए इस्तेमाल किया जाने वाला एक इंटरफ़ेस बनाएं:

public interface ApiServerRequests {

    @GET("api/get-servers")
    public Observable<List<Server>> getServers();
}

फिर एक Retrofit उदाहरण बनाएं:

public ApiRequests DeviceAPIHelper ()
{
    Gson gson = new GsonBuilder().create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://example.com/")
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

    api = retrofit.create(ApiServerRequests.class);
    return api;
}

फिर, कोड से कहीं भी विधि को कॉल करें:

apiRequests.getServers()
   .subscribeOn(Schedulers.io()) // the observable is emitted on io thread
   .observerOn(AndroidSchedulers.mainThread()) // Methods needed to handle request in background thread
   .subscribe(new Subscriber<List<Server>>() {
       @Override
       public void onCompleted() {
                    
       }

       @Override
       public void onError(Throwable e) {

       }

       @Override
       public void onNext(List<Server> servers) {
           //A list of servers is fetched successfully
       }
   });

RxJava के साथ रेट्रोफिट को डेटा को समान रूप से लाने के लिए

RxJava के GitHub रेपो से, RxJava रिएक्टिव एक्सटेंशन्स का एक जावा वीएम कार्यान्वयन है: अवलोकन योग्य अनुक्रमों का उपयोग करके अतुल्यकालिक और घटना-आधारित कार्यक्रमों की रचना करने के लिए एक पुस्तकालय। यह डेटा / घटनाओं के अनुक्रमों का समर्थन करने के लिए पर्यवेक्षक पैटर्न का विस्तार करता है और उन ऑपरेटरों को जोड़ता है जो आपको निम्न-स्तरीय थ्रेडिंग, सिंक्रनाइज़ेशन, थ्रेड-सेफ्टी और समवर्ती डेटा संरचनाओं जैसी चीज़ों के बारे में चिंताओं को दूर करते हुए क्रमिक रूप से एक साथ अनुक्रम बनाने की अनुमति देते हैं।

रिट्रोफिट एंड्रॉइड और जावा के लिए एक प्रकार-सुरक्षित HTTP क्लाइंट है, इसका उपयोग करके, डेवलपर्स सभी नेटवर्क सामानों को अधिक आसान बना सकते हैं। एक उदाहरण के रूप में, हम कुछ JSON को डाउनलोड करने और एक सूची के रूप में RecyclerView में दिखाने जा रहे हैं।

शुरू करना:

अपने एप्लिकेशन स्तर बिल्ड.gradle फ़ाइल में RxJava, RxAndroid और रेट्रोफिट निर्भरता जोड़ें: compile "io.reactivex:rxjava:1.1.6"
compile "io.reactivex:rxandroid:1.2.1"
compile "com.squareup.retrofit2:adapter-rxjava:2.0.2"
compile "com.google.code.gson:gson:2.6.2"
compile "com.squareup.retrofit2:retrofit:2.0.2"
compile "com.squareup.retrofit2:converter-gson:2.0.2"

सर्वर से डेटा का आदान-प्रदान करने के लिए ApiClient और ApiInterface को परिभाषित करें

public class ApiClient {

private static Retrofit retrofitInstance = null;
private static final String BASE_URL = "https://api.github.com/";

public static Retrofit getInstance() {
    if (retrofitInstance == null) {
        retrofitInstance = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofitInstance;
}

public static <T> T createRetrofitService(final Class<T> clazz, final String endPoint) {
    final Retrofit restAdapter = new Retrofit.Builder()
            .baseUrl(endPoint)
            .build();

    return restAdapter.create(clazz);
}

public static String getBaseUrl() {
    return BASE_URL;
}}

सार्वजनिक इंटरफ़ेस ApiInterface {

@GET("repos/{org}/{repo}/issues")
Observable<List<Issue>> getIssues(@Path("org") String organisation,
                                  @Path("repo") String repositoryName,
                                  @Query("page") int pageNumber);}

ध्यान दें कि getRepos () एक अवलोकन योग्य है और न केवल मुद्दों की सूची।

मॉडल परिभाषित करें

इसके लिए एक उदाहरण दिखाया गया है। आप JsonSchema2Pojo या इस जैसी मुफ्त सेवाओं का उपयोग कर सकते हैं।

public class Comment {

@SerializedName("url")
@Expose
private String url;
@SerializedName("html_url")
@Expose
private String htmlUrl;

//Getters and Setters
}

रेट्रोफिट उदाहरण बनाएं

ApiInterface apiService = ApiClient.getInstance().create(ApiInterface.class);

फिर, सर्वर से डेटा लाने के लिए इस उदाहरण का उपयोग करें

Observable<List<Issue>> issueObservable = apiService.getIssues(org, repo,                 pageNumber);
    issueObservable.subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .map(issues -> issues)    //get issues and map to issues list
            .subscribe(new Subscriber<List<Issue>>() {
                @Override
                public void onCompleted() {
                    Log.i(TAG, "onCompleted: COMPLETED!");
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(TAG, "onError: ", e);
                }

                @Override
                public void onNext(List<Issue> issues) {
                    recyclerView.setAdapter(new IssueAdapter(MainActivity.this, issues, apiService));
                }
            });

अब, आपने Retrofit और RxJava का उपयोग करते हुए सर्वर से सफलतापूर्वक डेटा प्राप्त किया है।

नेस्टेड अनुरोध उदाहरण: कई अनुरोध, परिणाम गठबंधन

मान लीजिए हमारे पास एक एपीआई है जो हमें एकल अनुरोध ( getAllPets ) में ऑब्जेक्ट मेटाडेटा प्राप्त करने की अनुमति देता है, और अन्य अनुरोध जिनके पास एकल संसाधन का पूरा डेटा है ( getSinglePet )। हम सभी को एक श्रृंखला में कैसे क्वेरी कर सकते हैं?

public class PetsFetcher {


static class PetRepository {
    List<Integer> ids;
}

static class Pet {
    int id;
    String name;
    int weight;
    int height;
}

interface PetApi {

    @GET("pets") Observable<PetRepository> getAllPets();

    @GET("pet/{id}") Observable<Pet> getSinglePet(@Path("id") int id);

}

PetApi petApi;

Disposable petsDisposable;

public void requestAllPets() {

    petApi.getAllPets()
            .doOnSubscribe(new Consumer<Disposable>() {
                @Override public void accept(Disposable disposable) throws Exception {
                    petsDisposable = disposable;
                }
            })
            .flatMap(new Function<PetRepository, ObservableSource<Integer>>() {
                @Override
                public ObservableSource<Integer> apply(PetRepository petRepository) throws Exception {
                    List<Integer> petIds = petRepository.ids;
                    return Observable.fromIterable(petIds);
                }
            })
            .flatMap(new Function<Integer, ObservableSource<Pet>>() {
                @Override public ObservableSource<Pet> apply(Integer id) throws Exception {
                    return petApi.getSinglePet(id);
                }
            })
            .toList()
            .toObservable()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<List<Pet>>() {
                @Override public void accept(List<Pet> pets) throws Exception {
                    //use your pets here
                }
            }, new Consumer<Throwable>() {
                @Override public void accept(Throwable throwable) throws Exception {
                    //show user something goes wrong
                }
            });

}

void cancelRequests(){
    if (petsDisposable!=null){
        petsDisposable.dispose();
        petsDisposable = null;
    }
}

}



Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow