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
11 changes: 8 additions & 3 deletions flowcats/src/main/java/otus/homework/flowcats/CatsRepository.kt
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
package otus.homework.flowcats

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow

class CatsRepository(
private val catsService: CatsService,
private val refreshIntervalMs: Long = 5000
) {

fun listenForCatFacts() = flow {
fun listenForCatFacts(): Flow<Result<Fact>> = flow {
while (true) {
val latestNews = catsService.getCatFact()
emit(latestNews)
try {
emit(Result.Success(catsService.getCatFact()))
} catch (e: Exception) {
emit(Result.Error(e))
break
}
delay(refreshIntervalMs)
}
}
Expand Down
27 changes: 19 additions & 8 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,41 @@ package otus.homework.flowcats

import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CatsViewModel(
private val catsRepository: CatsRepository
) : ViewModel() {

private val _catsLiveData = MutableLiveData<Fact>()
val catsLiveData: LiveData<Fact> = _catsLiveData
private val _catsState =
MutableStateFlow<Result<Fact>>(Result.Error(IllegalStateException("No data")))
val catsState: StateFlow<Result<Fact>> = _catsState.asStateFlow()

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
catsRepository.listenForCatFacts()
.collect { result ->
_catsState.value = result
}
}
}
}
}

class CatsViewModelFactory(private val catsRepository: CatsRepository) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T =
CatsViewModel(catsRepository) as T
}
}

sealed class Result<out T> {
data class Success<T>(val data: T) : Result<T>()
data class Error(val throwable: Throwable) : Result<Nothing>()
}
24 changes: 22 additions & 2 deletions flowcats/src/main/java/otus/homework/flowcats/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,39 @@ package otus.homework.flowcats
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
//import androidx.lifecycle.repeatOnLifecycle

class MainActivity : AppCompatActivity() {

private val diContainer = DiContainer()
private val catsViewModel by viewModels<CatsViewModel> { CatsViewModelFactory(diContainer.repository) }

@OptIn(InternalCoroutinesApi::class)
override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)
val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView
setContentView(view)

catsViewModel.catsLiveData.observe(this){
view.populate(it)

lifecycleScope.launch {
// repeatOnLifecycle(Lifecycle.State.STARTED) {
catsViewModel.catsState.collect { result ->
when (result) {
is Result.Success -> view.populate(result.data)
is Result.Error -> {
// минимально: лог или заглушка
// Log.e("MainActivity", "Error", result.throwable)
}
}
}
// }
}

}
}
1 change: 1 addition & 0 deletions operators/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'
implementation 'androidx.activity:activity-ktx:1.2.3'
// implementation "androidx.lifecycle:lifecycle-runtime-ktx"
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
}
42 changes: 37 additions & 5 deletions operators/src/main/java/otus/homework/flow/SampleInteractor.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package otus.homework.flow

import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.*

@ExperimentalCoroutinesApi
Expand All @@ -18,7 +19,12 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.map { it * 5 }
.filter { it > 20 }
.filter { it % 2 != 0 }
.map { "$it won" }
.take(3)
}

/**
Expand All @@ -28,8 +34,20 @@ class SampleInteractor(
* Если входное число делится на 15 - эмитим само число и после него эмитим строку FizzBuzz
* Если число не делится на 3,5,15 - эмитим само число
*/
@OptIn(FlowPreview::class)
fun task2(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.flatMapConcat { number ->
flow {
emit(number.toString())

when {
number % 15 == 0 -> emit("FizzBuzz")
number % 3 == 0 -> emit("Fizz")
number % 5 == 0 -> emit("Buzz")
}
}
}
}

/**
Expand All @@ -38,7 +56,10 @@ class SampleInteractor(
* Если айтемы в одно из флоу кончились то результирующий флоу также должен закончится
*/
fun task3(): Flow<Pair<String, String>> {
return flowOf()
return sampleRepository.produceColors()
.zip(sampleRepository.produceForms()) { color, form ->
color to form
}
}

/**
Expand All @@ -48,6 +69,17 @@ class SampleInteractor(
* При любом исходе, будь то выброс исключения или успешная отработка функции вызовите метод dotsRepository.completed()
*/
fun task4(): Flow<Int> {
return flowOf()
return sampleRepository.produceNumbers()
.catch { throwable ->
if (throwable is IllegalArgumentException) {
emit(-1)
} else {
throw throwable
}
}
.onCompletion {
sampleRepository.completed()
}
}
}
}