Rxjava interval로 Timer구현하기

2020. 4. 11. 23:23Dev

Rxjava2 interval 아래 문서에서 내용을 확인하시면 더 좋습니다.

 

http://reactivex.io/documentation/operators/interval.html

 

ReactiveX - Interval operator

RxGroovy implements this operator as interval. It accepts as its parameters a span of time to wait between emissions and the TimeUnit in which this span is measured. There is also a version of interval that returns an Observable that emits a single zero af

reactivex.io

 

Android에서 흔히 timer를 구현할 때는 Timer객체나 CountDownTimer를 사용하는데 이 방법에서 Rx를 사용한 방법으로 바꿔보는 시간

 

필요한 데이터 

  •  현재 시간
  •  종료 시간
  •  Tick period

 

현재 시간 

val currentDate = System.currentTimeMillis()

 

종료 시간

val endDate = System.currentTimeMillis() + (1000 * 60)

1분 후 종료 (Millisecond이라서 1000을 곱합니다.)

 

Tick period 

1초 

 


 

종료 시간과 현재 시간의 차이를 구합니다.

var diff: Long = endDate - currentDate 

 

interval operator 작성

Observable.interval(1, TimeUnit.SECONDS) // 1초마다.map {
	"[TIMER]" + convertTime(diff - it.convertToMillis()) } // 포맷에 맞게 수정 
    .take(diff, TimeUnit.MILLISECONDS) // 1초에 1개 발행 = 총 diff
    .doOnComplete { System.out.println("END") } // 완료된 후 작업
    .subscribe(System.out::println) // 구독

 

 

+ 유틸 메서드

SimpleDateFormat보다 TimeUnit의 convert method를 사용하여 구현하는 것이 더 적합하다고 생각합니다.

private fun convertTime(diff: Long): String = 
	" ${TimeUnit.MILLISECONDS.toDays(diff)} days " + 
	" ${TimeUnit.MILLISECONDS.toHours(diff) 
		- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(diff))} hours " +
	" ${TimeUnit.MILLISECONDS.toMinutes(diff) 
		- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(diff))} minutes " +
	" ${TimeUnit.MILLISECONDS.toSeconds(diff) 
		- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(diff))} seconds"
fun Long.convertToMillis() = this * 1000

 

안드로이드에서 CountDownTimer나 Timer를 구현하는 것보다 깔끔하고 결과나 작업 도중 UI에 표시할 때 유용할 것 같다고 생각됩니다.

 

 

 

 

'Dev' 카테고리의 다른 글

Video Streaming Structure (part1)  (0) 2020.04.14