-
Notifications
You must be signed in to change notification settings - Fork 128
/
TwoLongRunningTasksViewModel.kt
61 lines (53 loc) · 1.78 KB
/
TwoLongRunningTasksViewModel.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.mindorks.kotlinFlow.learn.task.twotasks
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mindorks.kotlinFlow.data.api.ApiHelper
import com.mindorks.kotlinFlow.data.local.DatabaseHelper
import com.mindorks.kotlinFlow.utils.Resource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
class TwoLongRunningTasksViewModel(
private val apiHelper: ApiHelper,
private val dbHelper: DatabaseHelper
) : ViewModel() {
private val status = MutableLiveData<Resource<String>>()
fun startLongRunningTask() {
viewModelScope.launch {
status.postValue(Resource.loading(null))
doLongRunningTaskOne()
.zip(doLongRunningTaskTwo()) { resultOne, resultTwo ->
return@zip resultOne + resultTwo
}
.flowOn(Dispatchers.Default)
.catch { e ->
status.postValue(Resource.error(e.toString(), null))
}
.collect {
status.postValue(Resource.success(it))
}
}
}
fun getStatus(): LiveData<Resource<String>> {
return status
}
private fun doLongRunningTaskTwo(): Flow<String> {
return flow {
// your code for doing a long running task
// Added delay to simulate
delay(5000)
emit("Two")
}
}
private fun doLongRunningTaskOne(): Flow<String> {
return flow {
// your code for doing a long running task
// Added delay to simulate
delay(5000)
emit("One")
}
}
}