Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Homework #180

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
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
9 changes: 9 additions & 0 deletions flowcats/src/main/java/otus/homework/flowcats/ApiResult.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package otus.homework.flowcats

sealed class ApiResult<out T> {

class Success<T>(val data: T): ApiResult<T>()
class Error(val e: Throwable): ApiResult<Nothing>()

data object Loading: ApiResult<Nothing>()
}
11 changes: 9 additions & 2 deletions flowcats/src/main/java/otus/homework/flowcats/CatsRepository.kt
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
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<ApiResult<Fact>> = flow {
while (true) {
val latestNews = catsService.getCatFact()
emit(ApiResult.Loading)
val latestNews = try {
val fact = catsService.getCatFact()
ApiResult.Success(fact)
} catch (e: Exception){
ApiResult.Error(e)
}
emit(latestNews)
delay(refreshIntervalMs)
}
Expand Down
11 changes: 7 additions & 4 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ 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.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
Expand All @@ -10,14 +13,14 @@ class CatsViewModel(
private val catsRepository: CatsRepository
) : ViewModel() {

private val _catsLiveData = MutableLiveData<Fact>()
val catsLiveData: LiveData<Fact> = _catsLiveData
private val _catsStF = MutableStateFlow<ApiResult<Fact>>(ApiResult.Loading)
val catsStF: StateFlow<ApiResult<Fact>> = _catsStF.asStateFlow()

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
_catsStF.value = it
}
}
}
Expand All @@ -26,6 +29,6 @@ class CatsViewModel(

class CatsViewModelFactory(private val catsRepository: CatsRepository) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
override fun <T : ViewModel> create(modelClass: Class<T>): T =
CatsViewModel(catsRepository) as T
}
16 changes: 14 additions & 2 deletions flowcats/src/main/java/otus/homework/flowcats/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ package otus.homework.flowcats

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

Expand All @@ -14,8 +18,16 @@ class MainActivity : AppCompatActivity() {
val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView
setContentView(view)

catsViewModel.catsLiveData.observe(this){
view.populate(it)
lifecycleScope.launchWhenResumed {
catsViewModel.catsStF.collectLatest { result ->
when (result) {
is ApiResult.Error -> Toast.makeText(this@MainActivity, result.e.toString(), Toast.LENGTH_LONG).show()
ApiResult.Loading -> {}
is ApiResult.Success -> view.populate(result.data)
}

}
}

}
}
27 changes: 23 additions & 4 deletions operators/src/main/java/otus/homework/flow/SampleInteractor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,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 @@ -29,7 +34,15 @@ class SampleInteractor(
* Если число не делится на 3,5,15 - эмитим само число
*/
fun task2(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.transform {
emit(it.toString())
when {
it % 15 == 0 ->{emit("FizzBuzz")}
it % 5 == 0 ->{emit("Buzz")}
it % 3 == 0 ->{emit("Fizz")}
}
}
}

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

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