Timer using Rxjava in android Interval operator

Checkout the previous posts

  1. Rxjava Introduction
  2. Reactive Hello world application in android

  3. Transformation using RxJava tutorial for beginners

  4. Introducing Operators in RxJava tutorial for beginners

 

Interval create an Observable that emits a sequence of integers spaced by a given time interval

Interval
The Interval operator returns an Observable that emits an infinite sequence of ascending integers, with a constant interval of time of your choosing between emissions.rxjava code look like this
Observable.interval(1, TimeUnit.SECONDS)
        .map((tick) -> {
            {...Write your code here          .......}
           return true;
        }).subscribe();

1) Create an activity as follows

package com.cretlabs.rxjavaintroduction;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

public class TimerActivity extends AppCompatActivity {
    Disposable disposable;
    Button start, stop;
    TextView textView;
    private long seconds;
    private Handler handler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timer);
        start = findViewById(R.id.button);
        stop = findViewById(R.id.button2);
        textView = findViewById(R.id.textView);
        start.setOnClickListener(view -> {
            startTimer();
        });
        stop.setOnClickListener(view -> {
            stopTimer();
        });


    }

    private void stopTimer() {
        if (disposable != null) {
            disposable.dispose();
        }
    }

    private void startTimer() {
        disposable = Observable.interval(1, TimeUnit.SECONDS)
                .map((tick) -> {
                    seconds += 1;
                    handler.post(() -> textView.setText(String.format(Locale.getDefault(), "%ds", seconds)));
                    return true;
                }).subscribe();
    }
}

2)activity_timer.xnl as follows

xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.cretlabs.rxjavaintroduction.TimerActivity">

    

 

 

 

Thanks happy Coding 😀

[sociallocker]Download Code Github [/sociallocker]

 

 

Categories: RxJava2

Leave a Reply

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

Social Media Auto Publish Powered By : XYZScripts.com