11package zlc.season.downloadx.downloader
22
33import kotlinx.coroutines.*
4- import kotlinx.coroutines.flow.Flow
5- import kotlinx.coroutines.flow.MutableStateFlow
6- import kotlinx.coroutines.flow.flatMapConcat
7- import kotlinx.coroutines.flow.flow
4+ import kotlinx.coroutines.flow.*
85import zlc.season.downloadx.Progress
96import zlc.season.downloadx.core.Default
107import zlc.season.downloadx.core.request
@@ -14,7 +11,6 @@ import zlc.season.downloadx.utils.fileName
1411import zlc.season.downloadx.utils.isSupportRange
1512import zlc.season.downloadx.utils.log
1613
17- @ExperimentalCoroutinesApi
1814open class DownloadTask (
1915 private val downloadParams : DownloadParams ,
2016 private val downloadConfig : DownloadConfig
@@ -24,9 +20,12 @@ open class DownloadTask(
2420
2521 private val coroutineScope = downloadConfig.coroutineScope ? : GlobalScope
2622
27- private val progressStateFlow = MutableStateFlow (0 )
23+ private val downloadStateFlow = MutableStateFlow (0 )
2824
2925 fun start () {
26+ if (downloadJob != null ) {
27+ downloadJob?.cancel()
28+ }
3029 downloadJob = coroutineScope.launch {
3130 val response = request(downloadParams.url, downloadConfig.header)
3231 if (! response.isSuccessful) {
@@ -42,44 +41,47 @@ open class DownloadTask(
4241 }
4342
4443 downloader = if (response.isSupportRange()) {
45- RangeDownloader (coroutineScope)
44+ NormalDownloader (coroutineScope)
4645 } else {
4746 NormalDownloader (coroutineScope)
4847 }
49- downloader?.download(downloadParams, downloadConfig, response)
50-
51- stateTrigger()
48+ val downloadJob = async {
49+ downloader?.download(downloadParams, downloadConfig, response)
50+ }
51+ val stateTriggerJob = async { stateTrigger() }
52+ downloadJob.join()
53+ stateTriggerJob.join()
5254 }
53- downloadJob?.start()
5455 }
5556
5657 fun stop () {
5758 downloadJob?.cancel()
5859 }
5960
61+ @FlowPreview
6062 fun progress (interval : Long = 100): Flow <Progress > {
61- // return progressStateFlow.flatMapConcat {
62- return flow {
63- var progress = progress()
64- // if (progress.isComplete()) {
65- // emit(progress)
66- // } else {
67- while (downloadJob?.isActive == true && ! progress.isComplete()) {
68- delay(interval)
69- progress = progress()
70- emit(progress)
63+ return downloadStateFlow.flatMapConcat {
64+ flow {
65+ var progress = progress()
66+ if (progress.isComplete()) {
67+ emit(progress)
68+ } else {
69+ while (downloadJob?.isActive == true && ! progress.isComplete()) {
70+ delay(interval)
71+ progress = progress()
72+ emit(progress)
73+ }
74+ }
7175 }
7276 }
73- // }
74- // }
7577 }
7678
7779 suspend fun progress (): Progress {
7880 return downloader?.queryProgress() ? : Progress ()
7981 }
8082
8183 private fun stateTrigger () {
82- progressStateFlow .value = progressStateFlow .value + 1
84+ downloadStateFlow .value = downloadStateFlow .value + 1
8385 }
8486
8587 private fun Progress.isComplete (): Boolean {
0 commit comments