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,11 @@ import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.flow.collect
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 +48,16 @@ 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()
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
loginViewModel.state.collect {
when (it) {
is LoginViewState.Login -> showLogin(it)
LoginViewState.LoggingIn -> showLoggingIn()
is LoginViewState.Content -> showContent(it)
LoginViewState.LoggingOut -> showLoggingOut()
}
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,63 @@ 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.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
private val loginApi = LoginApi()

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

private fun loginFlow(creds: Credentials): Flow<LoginViewState> = flow {
emit(LoginViewState.LoggingIn)
try {
val user = withContext(Dispatchers.IO) {
return@withContext loginApi.login(creds)
}
emit(LoginViewState.Content(user))
} catch (e: Exception) {
emit(LoginViewState.Login(e))
}
}

/**
* Logout from the network
*/
fun logout() {
// TODO: Implement logout
_state.value = LoginViewState.LoggingOut

viewModelScope.launch {
try {
withContext(Dispatchers.IO) {
return@withContext loginApi.logout()
}
_state.value = LoginViewState.Login()
} catch (e: Exception) {
_state.value = LoginViewState.Login(e)
}
}

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

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

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

viewModelScope.launch {
val results = mutableListOf<Result<Long>>()
withContext(Dispatchers.IO) {
repeat(numberOfThreads) {
val result = async { emulateBlockingNetworkRequest() }
results.add(result.await())
}
}

val successResults = results.mapNotNull { it.getOrNull() }

_result.value = successResults.average().toLong()
_running.value = false
}
}

private companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import ru.otus.coroutineshomework.databinding.FragmentTimerBinding
import java.util.Locale
Expand All @@ -25,6 +28,11 @@ class TimerFragment : Fragment() {
binding.time.text = newValue.toDisplayString()
}

private var timeFlow = MutableStateFlow(Duration.ZERO)
private var timerJob: Job? = null

private var timeDelay = 10.milliseconds

private var started by Delegates.observable(false) { _, _, newValue ->
setButtonsState(newValue)
if (newValue) {
Expand Down Expand Up @@ -53,12 +61,19 @@ 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()
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
timeFlow.collect {
time.text = it.toDisplayString()
}
}
}
time.text = this@TimerFragment.timeFlow.value.toDisplayString()
btnStart.setOnClickListener {
started = true
}
Expand All @@ -70,21 +85,28 @@ 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 fun startTimer() {
// TODO: Start timer
timerJob = lifecycleScope.launch {
while (started) {
delay(timeDelay)
timeFlow.emit(timeFlow.value + timeDelay )
}
}
}

private fun stopTimer() {
// TODO: Stop timer
timerJob?.cancel()
timerJob = null
}

override fun onDestroyView() {
super.onDestroyView()
_binding = null
stopTimer()
}

companion object {
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/res/values-night/themes.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.CoroutinesHomework" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<style name="Theme.CoroutinesHomework" parent="Theme.Material3.DayNight">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_200</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
Expand Down