-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.kt
62 lines (58 loc) · 1.72 KB
/
Main.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
62
import com.mmolosay.resource.Resource
import com.mmolosay.resource.ext.empty
import com.mmolosay.resource.ext.failure
import com.mmolosay.resource.ext.invoke
import com.mmolosay.resource.ext.loading
import com.mmolosay.resource.ext.success
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.random.Random
fun main() {
resourcePlainSample()
}
/**
* 'resource-plain' flavor usage showcase.
*/
fun resourcePlainSample() =
runBlocking {
val flow = MutableStateFlow(Resource.empty<String>())
launch {
flow.collect { resource ->
resource.invoke(
onEmpty = { println("empty") },
onLoading = { println("loading") },
onSuccess = { println("success, data=$it") },
onFailure = { println("failure, cause=$it") }
)
}
}
getData(flow)
}
/**
* Obtains data and propagates progress in specified [dest] flow.
*/
private suspend fun getData(dest: MutableStateFlow<Resource<String>>) {
dest.update { Resource.loading() }
try {
getDataAsync { data ->
dest.update { Resource.success(data) }
}
} catch (e: Exception) {
dest.update { Resource.failure(e) }
}
}
/**
* Simulates obtaining data asynchronously.
*/
private suspend fun getDataAsync(action: (data: String) -> Unit) {
delay(2_000L)
// randomly decide whether to return data or throw exception
if (Random.nextBoolean()) {
action("obtained data")
} else {
throw IllegalStateException("oops")
}
}