-
Notifications
You must be signed in to change notification settings - Fork 0
/
CalculationInBackgroundViewModel.kt
52 lines (45 loc) · 1.83 KB
/
CalculationInBackgroundViewModel.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
package com.lukaslechner.coroutineusecasesonandroid.usecases.coroutines.usecase10
import androidx.lifecycle.viewModelScope
import com.lukaslechner.coroutineusecasesonandroid.base.BaseViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.math.BigInteger
import kotlin.system.measureTimeMillis
class CalculationInBackgroundViewModel(
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
) : BaseViewModel<UiState>() {
fun performCalculation(factorialOf: Int) {
uiState.value = UiState.Loading
viewModelScope.launch {
try {
var result: BigInteger = BigInteger.ZERO
val computationDuration = measureTimeMillis {
result = calculateFactorialOf(factorialOf)
}
var resultString = ""
val stringConversionDuration = measureTimeMillis {
resultString = convertToString(result)
}
uiState.value =
UiState.Success(resultString, computationDuration, stringConversionDuration)
} catch (exception: Exception) {
UiState.Error("Error while calculating result")
}
}
}
// factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
private suspend fun calculateFactorialOf(number: Int): BigInteger =
withContext(defaultDispatcher) {
var factorial = BigInteger.ONE
for (i in 1..number) {
factorial = factorial.multiply(BigInteger.valueOf(i.toLong()))
}
factorial
}
private suspend fun convertToString(number: BigInteger): String =
withContext(defaultDispatcher) {
number.toString()
}
}