Kotlin - ViewModel

PHOTO EMBED

Wed Aug 04 2021 06:01:18 GMT+0000 (Coordinated Universal Time)

Saved by @GoodRequest.

class DebugViewModel: ViewModel() {
    private val _state: MutableStateFlow<Int> = MutableStateFlow(0)
    val state: StateFlow<Int> get() = _state

    fun calculateFactorialOf(n: Int) {
        viewModelScope.launch {
            var result = 1
            repeat(n) { i ->
                result = calculate(result, i)
            }
            _state.emit(result)
        }
    }

    private fun calculate(res: Int, i: Int): Int = res * i
}
content_copyCOPY