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.stateFlow.collect { viewState ->
when(viewState) {
is LoginViewState.Login -> showLogin(viewState)
LoginViewState.LoggingIn -> showLoggingIn()
is LoginViewState.Content -> showContent(viewState)
LoginViewState.LoggingOut -> showLoggingOut()
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,55 @@ package ru.otus.coroutineshomework.ui.login
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
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.flow.flowOn
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 _stateFlow = MutableStateFlow<LoginViewState>(LoginViewState.Login())
val stateFlow: StateFlow<LoginViewState> = _stateFlow.asStateFlow()
val loginApi = LoginApi()

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

/**
* Logout from the network
*/
fun logout() {
// TODO: Implement logout
fun logout(){
viewModelScope.launch {
logoutFlow().collect {
_stateFlow.emit(it)
}
}
}

fun loginFlow(name: String, password: String) = flow<LoginViewState> {
emit(LoginViewState.LoggingIn)
val credentials = Credentials(name, password)
try {
val user = loginApi.login(credentials)
emit(LoginViewState.Content(user))
} catch (e: Exception){
emit(LoginViewState.Login(e))
}
}.flowOn(Dispatchers.IO)

fun logoutFlow() = flow<LoginViewState> {
emit(LoginViewState.LoggingOut)
loginApi.logout()
emit(LoginViewState.Login())
}.flowOn(Dispatchers.IO)
}
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,21 @@ class NetworkViewModel : ViewModel() {
val result: LiveData<Long?> = _result

fun startTest(numberOfThreads: Int) {
// TODO: Implement the logic
viewModelScope.launch {
_running.value = true
_result.value = null
val jobs = List(numberOfThreads) {
async { emulateBlockingNetworkRequest() }
}
val successfulTimeList = jobs.mapNotNull { it.await().getOrNull() }
val averageTime = if (successfulTimeList.isNotEmpty()) {
successfulTimeList.average().toLong()
} else {
0L
}
_result.value = averageTime
_running.value = false
}
}

private companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@ 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.flow.flow
import kotlinx.coroutines.launch
import ru.otus.coroutineshomework.databinding.FragmentTimerBinding
import java.util.Locale
Expand All @@ -20,10 +24,8 @@ 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 var job: Job? = null
private val timeFlow = MutableStateFlow<Duration>(Duration.ZERO)

private var started by Delegates.observable(false) { _, _, newValue ->
setButtonsState(newValue)
Expand Down Expand Up @@ -53,12 +55,18 @@ 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 {
repeatOnLifecycle(Lifecycle.State.STARTED) {
timeFlow.collect {
time.text = it.toDisplayString()
}
}
}
btnStart.setOnClickListener {
started = true
}
Expand All @@ -70,16 +78,21 @@ 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
job = viewLifecycleOwner.lifecycleScope.launch {
while (true){
delay(1)
timeFlow.emit(timeFlow.value + 1.milliseconds)
}
}
}

private fun stopTimer() {
// TODO: Stop timer
job?.cancel()
}

override fun onDestroyView() {
Expand All @@ -94,9 +107,9 @@ class TimerFragment : Fragment() {
private fun Duration.toDisplayString(): String = String.format(
Locale.getDefault(),
"%02d:%02d.%03d",
this.inWholeMinutes.toInt(),
this.inWholeSeconds.toInt(),
this.inWholeMilliseconds.toInt()
this.inWholeMinutes.toInt().mod(60),
this.inWholeSeconds.toInt().mod(60),
this.inWholeMilliseconds.toInt().mod(1000)
)
}
}
2 changes: 2 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ junit = "4.13.2"
junitVersion = "1.2.1"
espressoCore = "3.6.1"
appcompat = "1.7.0"
kotlinxTime = "0.5.0"
material = "1.12.0"
constraintlayout = "2.2.0"
lifecycleLivedataKtx = "2.8.7"
Expand All @@ -21,6 +22,7 @@ junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
kotlinx-time = { module = "org.jetbrains.kotlin:kotlinx-time", version.ref = "kotlinxTime" }
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" }
androidx-lifecycle-livedata-ktx = { group = "androidx.lifecycle", name = "lifecycle-livedata-ktx", version.ref = "lifecycleLivedataKtx" }
Expand Down