1. 비동기란?
비동기 프로그래밍은 프로그램이 여러 작업을 동시에 수행하거나, 하나의 작업이 완료될 때까지 기다리지 않고 다른 작업을 계속 수행할 수 있도록 도와주는 패러다임을 뜻한다. 주로 I/O 작업이나 통신과 같이 시간이 오래 걸리는 작업에 많이 사용되고 있다. 특히 소켓통신, 웹소켓, 대량의 데이터를 불러오는 작업(사진첩 및 연락처)에 유용하다.
2. Handler 및 Timer
(1) Handler
주로 안드로이드에서 많이 사용되며, Timer와 다르게 UI를 사용할 수 있는 부분에서 차이가 있다. 메시지큐와 함께 사용되는 비동기 처리 도구이다.
CODE
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
// UI 업데이트 작업
textView.setText("Hello, Handler!");
}
});
(2) Timer
일정 시간 간격으로 작업을 수행하기 위해 타이머 기능을 사용한다. 일반적으로 자바에서 많이 사용된다.
CODE
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// 주기적으로 실행되는 작업
System.out.println("Timer Task executed!");
}
}, 0, 1000); // 초기 지연 0밀리초, 주기 1초
(3) Coroutine
코루틴은 경량 스레드와 같이 동작하는 비동기 처리 방식이다. Kotlin에서 제공되며 코드블럭 단위로 나누어 실행하면서 중단 및 재개할 수 있도록한다. 비동기 작업을 동기적으로 비동기적으로 작성할 수 있도록 도와준다.
CODE
import kotlinx.coroutines.*
fun main() {
// GlobalScope.launch는 전역 범위에서 실행되는 코루틴을 만든다.
GlobalScope.launch {
println("Start Coroutine") // 1. 실행 시작
delay(1000) // 2. 1초 동안 일시 중단
println("End Coroutine") // 3. 일시 중단 후 실행 재개
}
// 메인 스레드는 코루틴이 끝나길 기다리지 않고 바로 종료.
println("Main Thread: Coroutine is launched")
// 코루틴이 실행될 동안 메인 스레드는 다른 작업을 수행할 수 있다.
Thread.sleep(2000) // 4. 메인 스레드는 2초 동안 일시 중단
}
(4) RxJava, RxKotlin
Reactive Extensions의 일부로, 비동기 및 이벤트 기반 프로그래밍을 위한 라이브러리 이다. 즉 Observable 시퀀스를 통해 데이터나 이벤트를 처리하고 옵저버 패턴을 사용하여 데이터의 변화에 대응한다. RxJava는 자바용, RxKotlin은 코틀린용이다. 주로 이벤트스트림, 데이터 스트림을 처리하고 조합하는데 사용된다.
CODE
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
public class RxJavaExample {
public static void main(String[] args) {
// Observable 생성
Observable<String> observable = Observable.just("test");
// Observable<String> observable = Observable.fromArray("One", "Two", "Three");
// Observer 생성
Observer<String> observer = new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
};
// Observable을 Observer에 연결
observable.subscribe(observer);
}
}
- onSubscribe : 옵저버가 옵저버블을 구독할 때 호출한다.
- onNext : 옵저버블이 새로운 데이터를 발행할 때 호출, 여기서 String은 test를 출력한다. (단일 데이터 출력)
- onError : 에러가 발생했을 때 호출한다.
- onComplete : 데이터를 성공적으로 발행하고 완료될 때 호출한다.
Kotlin에서는 경량 Thread로 Coroutine이 널리 사용되고 있고 좀 더 심도 있는 과정은 RxKotlin이 사용된다고 생각하자.
상기의 예시 코드와는 다르게 emitter로 상시 데이터를 옵저버로 받아 데이터를 사용할 수 있도록 구현할 수도 있다. 어떤 코드가 더 효율적인지는 구현해 봐야 할 것 같지만 실시간 양방향 통신인 Socket에서 생각해 봤을 때 emitter로 데이터를 받는 편이 더 효율적일 것으로 판단된다.
Socket에서는 패킷 전송 시 비동기가 필요한데 이런 과정에서 RxKotlin를 사용하여 Thread를 좀 더 효율적으로 짜보는 연습도 좋은 것 같다.
'Android > Android Java-Kotlin' 카테고리의 다른 글
[Android Java Kotlin] companion object와 static (0) | 2023.10.27 |
---|---|
[Android Java Kotlin] equals와 ==의 차이(===) (0) | 2023.10.26 |
[Android Java Kotlin] List vs Array vs MutableList vs ArrayList vs LinkedList (0) | 2023.10.24 |
[Android Java Kotlin] View 숨기기 (0) | 2023.10.23 |