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
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ android {
}

dependencies {
implementation(libs.androidx.media3.common.ktx)
coreLibraryDesugaring(libs.desugar)

implementation(libs.androidx.core.ktx)
Expand Down
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,66 @@
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
import ru.otus.coroutineshomework.ui.login.data.User

class LoginViewModel : ViewModel() {
class LoginViewModel(private val loginApi: LoginApi = LoginApi()) : ViewModel() {

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

private fun loginFlow(credentials: Credentials?): Flow<LoginViewState> {
return flow {
try {
if (credentials != null) {
emit(LoginViewState.LoggingIn)
val user: User = withContext(Dispatchers.IO) {
loginApi.login(credentials)
}
emit(LoginViewState.Content(user))
} else {
emit(LoginViewState.LoggingOut)
withContext(Dispatchers.IO) {
loginApi.logout()
}
emit(LoginViewState.Login())
}
}
catch (exception: Exception) {
emit(LoginViewState.Login(error = exception))
}
}
}

/**
* 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 {
stateFlow.value = it
}
}
}

/**
* Logout from the network
*/
fun logout() {
// TODO: Implement logout
viewModelScope.launch {
loginFlow(null).collect {
stateFlow.value = it
}
}
}
}
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,25 @@ class NetworkViewModel : ViewModel() {
val result: LiveData<Long?> = _result

fun startTest(numberOfThreads: Int) {
// TODO: Implement the logic
viewModelScope.launch {
val resultList = mutableListOf<Deferred<Result<Long>>>()
_running.value = true
repeat(numberOfThreads) {
resultList.add(async(Dispatchers.IO) {
emulateBlockingNetworkRequest()
})
}

val results = resultList.awaitAll().mapNotNull { it.getOrNull() }

_running.value = false

if (results.isNotEmpty()) {
_result.value = results.average().toLong()
} else {
_result.value = null
}
}
}

private companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,31 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.coroutineScope
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import ru.otus.coroutineshomework.databinding.FragmentTimerBinding
import java.util.Locale
import kotlin.coroutines.coroutineContext
import kotlin.properties.Delegates
import kotlin.time.Duration
import kotlin.time.Duration.Companion.ZERO
import kotlin.time.Duration.Companion.milliseconds

class TimerFragment : Fragment() {

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

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

private var started by Delegates.observable(false) { _, _, newValue ->
setButtonsState(newValue)
Expand Down Expand Up @@ -53,12 +59,18 @@ class TimerFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
savedInstanceState?.let {
time = it.getLong(TIME).milliseconds
timeFlow = MutableStateFlow(it.getLong(TIME).milliseconds)
started = it.getBoolean(STARTED)
}
setButtonsState(started)
with(binding) {
time.text = this@TimerFragment.time.toDisplayString()
lifecycleScope.launch {
viewLifecycleOwner.lifecycle.repeatOnLifecycle(androidx.lifecycle.Lifecycle.State.STARTED) {
timeFlow.collect { duration->
time.text = duration.toDisplayString()
}
}
}
btnStart.setOnClickListener {
started = true
}
Expand All @@ -70,16 +82,27 @@ 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 createTimerFlow(initial: Long): Flow<Duration> = flow {
while(coroutineContext.isActive) {
emit((System.currentTimeMillis()-initial).milliseconds)
delay(15)
}
}

private fun startTimer() {
// TODO: Start timer
job = lifecycle.coroutineScope.launch {
createTimerFlow(System.currentTimeMillis()).collect {
timeFlow.value = it
}
}
}

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

override fun onDestroyView() {
Expand All @@ -94,9 +117,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()%60,
this.inWholeSeconds.toInt()%60,
this.inWholeMilliseconds.toInt()%1000
)
}
}
18 changes: 10 additions & 8 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
[versions]
agp = "8.7.3"
agp = "8.10.1"
kotlin = "2.1.0"
coreKtx = "1.15.0"
coreKtx = "1.16.0"
junit = "4.13.2"
junitVersion = "1.2.1"
espressoCore = "3.6.1"
appcompat = "1.7.0"
material = "1.12.0"
constraintlayout = "2.2.0"
lifecycleLivedataKtx = "2.8.7"
lifecycleViewmodelKtx = "2.8.7"
navigationFragmentKtx = "2.8.5"
navigationUiKtx = "2.8.5"
constraintlayout = "2.2.1"
lifecycleLivedataKtx = "2.9.0"
lifecycleViewmodelKtx = "2.9.0"
navigationFragmentKtx = "2.9.0"
navigationUiKtx = "2.9.0"
coroutines = "1.9.0"
desugar = "1.1.5"
desugar = "2.1.5"
media3CommonKtx = "1.7.1"

[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
Expand All @@ -29,6 +30,7 @@ androidx-navigation-fragment-ktx = { group = "androidx.navigation", name = "navi
androidx-navigation-ui-ktx = { group = "androidx.navigation", name = "navigation-ui-ktx", version.ref = "navigationUiKtx" }
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }
desugar = { group = "com.android.tools", name = "desugar_jdk_libs", version.ref = "desugar" }
androidx-media3-common-ktx = { group = "androidx.media3", name = "media3-common-ktx", version.ref = "media3CommonKtx" }

[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
Expand Down
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#Tue Jan 07 11:05:09 CET 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists