Skip to content

gokul42252/RxJavaNetworkCall

Repository files navigation

Network API request Using Rxjava android tutorial Beginner

Checkout the previous post http://thoughtnerds.com/reactive-hello-world-application-android/

for structure.

[amazon_link asins='1617293369,1784399108,9352134664,B071VG1VY9,B073L5JB27,1787120422,1484214293,1489138714,B0784QQV4W' template='ProductCarousel' store='200' marketplace='IN' link_id='3e407a04-34c3-11e8-9779-9bef6361f84b']

Adding RxJava 2 library  to a Java project in Android Studio

To use RxJava in a Gradle build, add the following as dependency.

compile group: 'io.reactivex.rxjava2', name: 'rxjava', version: '2.1.1'

For Maven, you can add RxJava via the following snippet.

<dependency>
    <groupId>io.reactivex.rxjava2</groupId>
    <artifactId>rxjava</artifactId>
    <version>2.0.4</version>
</dependency>

Since we are about to perform a network call, do not forget to add internet permission to your app manifest.

<uses-permission android:name="android.permission.INTERNET" />

1)Make sure you have a helper class for performing network calls. If you don’t have one, no worries. I got you covered. You can use this.

NetworkCall.java

package com.cretlabs.rxjavaintroduction.utils;


import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class NetworkCall {

    private int responseCode;

    public String makeServiceCall(String url){
        HttpURLConnection connection = null;
        String response = null;
        InputStream is = null;

        try {
            URL imgUrl = new URL(url);
            connection = (HttpURLConnection) imgUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            responseCode = connection.getResponseCode();
            is = connection.getInputStream();
            response = readIt(is);
            Log.d("response",response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    connection.disconnect();
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    private String readIt(InputStream iStream) throws Exception {
        String singleLine = "";
        StringBuilder totalLines = new StringBuilder(iStream.available());
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(iStream));

            while ((singleLine = reader.readLine()) != null) {
                totalLines.append(singleLine);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return totalLines.toString();
    }

}

2)Create an activity NetworkingActivity.java as Follows

package com.cretlabs.rxjavaintroduction;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.util.Log;

import com.cretlabs.rxjavaintroduction.utils.NetworkCall;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class NetworkingActivity extends AppCompatActivity {
    private static final String TAG = "NetworkingActivity";
    NetworkCall networkCall;
    AppCompatTextView mAppCompatTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_networking);
        mAppCompatTextView = findViewById(R.id.AN_txt);
        networkCall = new NetworkCall();
        Observer<String> networkCallObserver = new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.d(TAG, "onSubscribe() called with: d = [" + d + "]");
            }

            @Override
            public void onNext(String s) {
                Log.d(TAG, "onNext() called with: s = [" + s + "]");
                mAppCompatTextView.setText(s);
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "onError() called with: e = [" + e + "]");
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "onComplete() called");
            }
        };

        getDataFromServer().subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(networkCallObserver);

    }

    public Observable<String> getDataFromServer() {
        return Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                try {
                    String response = networkCall.makeServiceCall("http://thoughtnerds.com/api/get_recent_posts/");
                    emitter.onNext(response);
                } catch (Exception e) {
                    emitter.onError(e);
                }
            }
        });
    }

}

3)In this we created a custom observer

public Observable<String> getDataFromServer() {
    return Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(ObservableEmitter<String> emitter) throws Exception {
            try {
                String response = networkCall.makeServiceCall("http://thoughtnerds.com/api/get_recent_posts/");
                emitter.onNext(response);
            } catch (Exception e) {
                emitter.onError(e);
            }
        }
    });
}

4)After Creating function subscribe the Observable from OnCreate

getDataFromServer().subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(networkCallObserver);

Thus we can get response in OnNext in the networkCallObserver and set data to a textView

Network API request Using Rxjava android tutorial Beginner

[amazon_link asins='B073L5JB27,B071VG1VY9,9352134664,1787120422,1784399108,1617293369,B0784QQV4W,1489138714,1484214293' template='ProductCarousel' store='200' marketplace='IN' link_id='0befa111-34c7-11e8-a19e-036de9469172']

Thanks Happy Coding :D


 

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages