Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import ru.otus.coroutineshomework.databinding.ContentBinding
import ru.otus.coroutineshomework.databinding.FragmentLoginBinding
import ru.otus.coroutineshomework.databinding.LoadingBinding
Expand Down Expand Up @@ -43,12 +45,14 @@ class LoginFragment : Fragment() {
setupLogin()
setupContent()

loginViewModel.state.observe(viewLifecycleOwner) {
when(it) {
is LoginViewState.Login -> showLogin(it)
LoginViewState.LoggingIn -> showLoggingIn()
is LoginViewState.Content -> showContent(it)
LoginViewState.LoggingOut -> showLoggingOut()
lifecycleScope.launch {
loginViewModel.state.collect { state ->
when (state) {
is LoginViewState.Login -> showLogin(state)
LoginViewState.LoggingIn -> showLoggingIn()
is LoginViewState.Content -> showContent(state)
LoginViewState.LoggingOut -> showLoggingOut()
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,53 @@
package ru.otus.coroutineshomework.ui.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import ru.otus.coroutineshomework.ui.login.data.Credentials

class LoginViewModel : ViewModel() {

private val _state = MutableLiveData<LoginViewState>(LoginViewState.Login())
val state: LiveData<LoginViewState> = _state
private val _state = MutableStateFlow<LoginViewState>(LoginViewState.Login())
val state: StateFlow<LoginViewState> = _state.asStateFlow()

private fun loginFlow(credentials: Credentials): Flow<LoginViewState> =
flow {
val result = withContext(Dispatchers.IO) {
runCatching { LoginApi().login(credentials) }
}
result.onSuccess { emit(LoginViewState.Content(it)) }
result.onFailure { emit(LoginViewState.Login(it as Exception)) }
}

/**
* Login to the network
* @param name user name
* @param password user password
*/
fun login(name: String, password: String) {
// TODO: Implement login
_state.value = LoginViewState.LoggingIn
viewModelScope.launch {
loginFlow(Credentials(name, password)).collect {
_state.value = it
}
}
}

/**
* Logout from the network
*/
fun logout() {
// TODO: Implement logout
_state.value = LoginViewState.LoggingOut
viewModelScope.launch(Dispatchers.IO) {
LoginApi().logout()
}
_state.value = LoginViewState.Login()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Обратите внимание, что у вас состояние экрана меняется синхронно, а логаут выполняется асинхронно. Соответственно, состояние экрана не соответствует реальному состоянию системы. Логаут может занять несколько секунд и вернуть ошибку, например

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,13 @@ import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.random.Random

Expand All @@ -18,7 +23,23 @@ class NetworkViewModel : ViewModel() {
val result: LiveData<Long?> = _result

fun startTest(numberOfThreads: Int) {
// TODO: Implement the logic
_running.value = true
_result.value = null

val deferredResults = mutableListOf<Deferred<Result<Long>>>()

viewModelScope.launch {
repeat(numberOfThreads) {
deferredResults.add(async(Dispatchers.IO) { emulateBlockingNetworkRequest() })
}
val results = deferredResults.awaitAll()

val successCount = results.count { it.isSuccess }

_running.value = false
_result.value = if (successCount == 0) null else
results.filter { res -> res.isSuccess }.sumOf { it.getOrNull() ?: 0 } / successCount
}
}

private companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,27 @@ import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import ru.otus.coroutineshomework.databinding.FragmentTimerBinding
import java.time.Instant
import java.util.Locale
import kotlin.properties.Delegates
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.DurationUnit
import kotlin.time.toDuration

class TimerFragment : Fragment() {

private var _binding: FragmentTimerBinding? = null
private val binding get() = _binding!!

private var time: Duration by Delegates.observable(Duration.ZERO) { _, _, newValue ->
binding.time.text = newValue.toDisplayString()
}
private val timeFlow = MutableStateFlow(Duration.ZERO)

private var started by Delegates.observable(false) { _, _, newValue ->
setButtonsState(newValue)
Expand Down Expand Up @@ -53,12 +56,17 @@ class TimerFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
savedInstanceState?.let {
time = it.getLong(TIME).milliseconds
timeFlow.value = it.getLong(TIME).milliseconds
started = it.getBoolean(STARTED)
}
setButtonsState(started)
with(binding) {
time.text = this@TimerFragment.time.toDisplayString()
lifecycleScope.launch {
timeFlow.collect {
time.text = this@TimerFragment.timeFlow.value.toDisplayString()
}
}

btnStart.setOnClickListener {
started = true
}
Expand All @@ -70,16 +78,35 @@ class TimerFragment : Fragment() {

override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putLong(TIME, time.inWholeMilliseconds)
outState.putLong(TIME, timeFlow.value.inWholeMilliseconds)
outState.putBoolean(STARTED, started)
}

private lateinit var timerStartedAt: Instant

private fun getTimeDuration(): Duration {
return (Instant.now().toEpochMilli() - timerStartedAt.toEpochMilli()).toDuration(
DurationUnit.MILLISECONDS
)
}

private fun doTimerLoops() =
flow {
while (started) {
emit(getTimeDuration())
delay(16) // 1/60 Hz
}
}

private fun startTimer() {
// TODO: Start timer
CoroutineScope(Dispatchers.Main).launch {
doTimerLoops().collect { duration -> timeFlow.value = duration }
}
timerStartedAt = Instant.now()
}

private fun stopTimer() {
// TODO: Stop timer
timeFlow.value = getTimeDuration()
}

override fun onDestroyView() {
Expand All @@ -96,7 +123,7 @@ class TimerFragment : Fragment() {
"%02d:%02d.%03d",
this.inWholeMinutes.toInt(),
this.inWholeSeconds.toInt(),
this.inWholeMilliseconds.toInt()
this.inWholeMilliseconds.toInt().mod(1000)
)
}
}