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,10 @@ 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.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 +47,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.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
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
Expand Up @@ -3,25 +3,54 @@ 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.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import ru.otus.coroutineshomework.ui.login.data.Credentials

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 _state = MutableStateFlow<LoginViewState>(LoginViewState.Login())
val state: StateFlow<LoginViewState> = _state

/**
* Login to the network
* @param name user name
* @param password user password
*/
fun login(name: String, password: String) {
// TODO: Implement login
viewModelScope.launch {
_state.emit(LoginViewState.LoggingIn)
try {
val user = withContext(Dispatchers.IO){
loginApi.login(Credentials(name, password))
}
_state.emit(LoginViewState.Content(user))
}
catch (ex: Exception){
_state.emit(LoginViewState.Login(error = ex))
}
}
}

/**
* Logout from the network
*/
fun logout() {
// TODO: Implement logout
viewModelScope.launch {
_state.emit(LoginViewState.LoggingOut)
try {
withContext(Dispatchers.IO){
loginApi.logout()
}
_state.emit(LoginViewState.Login())
}
catch (ex: Exception){
_state.emit(LoginViewState.Login(error = ex))
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import kotlin.random.Random
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class NetworkViewModel : ViewModel() {

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

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

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

repeat(numberOfThreads) {
val job = async {
emulateBlockingNetworkRequest()
}
ranJobs.add(job)
}

val results = ranJobs.mapNotNull { it.await().getOrNull() }

if (results.isNotEmpty()) {
val averageTime = results.average().toLong()
_result.value = averageTime
} else {
_result.value = null
}
_running.value = false
}
}

private companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,34 @@ import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.collection.emptyLongSet
import androidx.fragment.app.Fragment
import androidx.lifecycle.coroutineScope
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.Job
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import ru.otus.coroutineshomework.databinding.FragmentTimerBinding
import java.util.Calendar
import java.util.Locale
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 time: Duration by Delegates.observable(Duration.ZERO) { _, _, newValue ->
binding.time.text = newValue.toDisplayString()
}
private var timerJob: Job? = null

private var timeFlow: MutableStateFlow<Duration> = MutableStateFlow(ZERO)

private var started by Delegates.observable(false) { _, _, newValue ->
setButtonsState(newValue)
Expand Down Expand Up @@ -53,12 +61,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()
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.lifecycle.repeatOnLifecycle(androidx.lifecycle.Lifecycle.State.STARTED) {
timeFlow.collect { duration ->
binding.time.text = duration.toDisplayString()
}
}
}
btnStart.setOnClickListener {
started = true
}
Expand All @@ -70,16 +84,24 @@ 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
stopTimer()
timerJob = lifecycle.coroutineScope.launch {
val prevTime = System.currentTimeMillis()
while(isActive){
val curTime = System.currentTimeMillis()
timeFlow.emit((curTime-prevTime).milliseconds)
delay(DELAY)
}
}
}

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

override fun onDestroyView() {
Expand All @@ -91,6 +113,8 @@ class TimerFragment : Fragment() {
private const val TIME = "time"
private const val STARTED = "started"

private const val DELAY:Long = 50

private fun Duration.toDisplayString(): String = String.format(
Locale.getDefault(),
"%02d:%02d.%03d",
Expand Down