0

Here's a sample code of http request in Java:

URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");

What's the best way to combine HttpURLConnection and RxJava?

My current option is:

Observable.defer(() -> {
   return sendHttpRequest(); // uses HttpURLConnection and returns a response's content as a string
});
James Larkin
  • 541
  • 5
  • 18
  • Possible duplicate of https://stackoverflow.com/questions/45381841/how-to-make-a-http-request-to-check-a-content-type-with-rxjava-2 – Varun Jain Aug 20 '19 at 04:55
  • @VarunJain I did see that question but I'm not concerned about using main thread / I don't think using `.just()` is a good approach here. – James Larkin Aug 20 '19 at 04:57
  • No, just() method can be used in the way mentioned in the link in 1st comment. But I want to know why just() is not a good approach and what is basis of your saying because I haven't found anywhere mentioned like that! – Varun Jain Aug 20 '19 at 05:05
  • https://stackoverflow.com/a/52671715/10946826 – James Larkin Aug 20 '19 at 05:08
  • Yeah, as the statement mentioned in the link, you are still free to use just or from as per your needs. So if you needs can be sufficed by lazily then you can use from otherwise just is also fine! – Varun Jain Aug 20 '19 at 05:23

1 Answers1

0

You can use a Callable. I've already written an answer on how to do this here.

java Observable.fromCallable((Callable<Object>) () -> {
    // do stuff
    return object;
})
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                // so that this can be properly disposed in onDestroy()
                compositeDisposable.add(d);
            }

            @Override
            public void onNext(@NonNull Object object) {
                // do stuff with the result
            }

            @Override
            public void onError(@NonNull Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
Sujit
  • 1,653
  • 2
  • 9
  • 25