Network API request Using Rxjava android tutorial Beginner

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

for structure.

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.


    io.reactivex.rxjava2
    rxjava
    2.0.4

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 networkCallObserver = new Observer() {
            @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 getDataFromServer() {
        return Observable.create(new ObservableOnSubscribe() {
            @Override
            public void subscribe(ObservableEmitter 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 getDataFromServer() {
    return Observable.create(new ObservableOnSubscribe() {
        @Override
        public void subscribe(ObservableEmitter 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

Get Full Source code on Download Github Project

Thanks Happy Coding 😀


 
Categories: RxJava2

Leave a Reply

Your email address will not be published. Required fields are marked *

Social Media Auto Publish Powered By : XYZScripts.com