본문 바로가기
안드로이드 코틀린

[Kotlin][Android] Rxkotlin 이용한 스레드

by teamnova 2021. 9. 9.

1. build.gradle 설정

    implementation 'io.reactivex.rxjava3:rxkotlin:3.0.0'

2. Mainactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">


    <Button
        android:id="@+id/startbtn"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:text="Start!!"
        app:layout_constraintBottom_toTopOf="@id/textView"
        android:layout_marginBottom="40dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

    <Button

        android:id="@+id/stopbtn"
        android:layout_width="wrap_content"
        android:layout_height="40dp"

        android:text="Stop!!"
        app:layout_constraintBottom_toTopOf="@id/textView"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

3.MainActivity

package com.example.videoapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import io.reactivex.rxjava3.core.Observable
import java.util.*
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        var tv = findViewById(R.id.textView) as TextView;
        var startbtn = findViewById(R.id.startbtn) as Button;




        tv.text = "0"


        startbtn.setOnClickListener {
            startbtn.isClickable = false

            Observable
                    .interval(0, 1, TimeUnit.SECONDS)
                    .subscribe {
                        runOnUiThread {
                            tv.text = it.toString()
                        }
                    }
        }





    }
}