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 {
val latestNews = catsService.getCatFact()
emit(Result.Success(latestNews))
} catch (e: Exception) {
emit(Result.Error(e))
}
delay(refreshIntervalMs)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import retrofit2.http.GET

interface CatsService {

@GET("random?animal_type=cat")
@GET("fact")
suspend fun getCatFact(): Fact
}
2 changes: 1 addition & 1 deletion flowcats/src/main/java/otus/homework/flowcats/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class CatsView @JvmOverloads constructor(
) : ConstraintLayout(context, attrs, defStyleAttr), ICatsView {

override fun populate(fact: Fact) {
findViewById<TextView>(R.id.fact_textView).text = fact.text
findViewById<TextView>(R.id.fact_textView).text = fact.fact
}
}

Expand Down
28 changes: 15 additions & 13 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,32 @@ package otus.homework.flowcats

import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

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

private val _catsLiveData = MutableLiveData<Fact>()
val catsLiveData: LiveData<Fact> = _catsLiveData
private val _cats = MutableStateFlow<Result<Fact>>(Result.Success(Fact()))
val cats: StateFlow<Result<Fact>> = _cats.asStateFlow()

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
}
}
}
catsRepository.listenForCatFacts()
.flowOn(Dispatchers.IO)
.onEach {
_cats.value = it
}.launchIn(viewModelScope)
}
}

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
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class DiContainer {

private val retrofit by lazy {
Retrofit.Builder()
.baseUrl("https://cat-fact.herokuapp.com/facts/")
.baseUrl("https://catfact.ninja/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
Expand Down
22 changes: 4 additions & 18 deletions flowcats/src/main/java/otus/homework/flowcats/Fact.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,8 @@ package otus.homework.flowcats
import com.google.gson.annotations.SerializedName

data class Fact(
@field:SerializedName("createdAt")
val createdAt: String,
@field:SerializedName("deleted")
val deleted: Boolean,
@field:SerializedName("_id")
val id: String,
@field:SerializedName("text")
val text: String,
@field:SerializedName("source")
val source: String,
@field:SerializedName("used")
val used: Boolean,
@field:SerializedName("type")
val type: String,
@field:SerializedName("user")
val user: String,
@field:SerializedName("updatedAt")
val updatedAt: String
@field:SerializedName("fact")
val fact: String = "",
@field:SerializedName("length")
val length: Int = 0
)
20 changes: 17 additions & 3 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,12 @@ 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.launchIn
import kotlinx.coroutines.flow.onEach
import java.net.SocketTimeoutException

class MainActivity : AppCompatActivity() {

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

catsViewModel.catsLiveData.observe(this){
view.populate(it)
}
catsViewModel.cats.onEach {
when (it) {
is Result.Error -> {
val message = when(it.error) {
is SocketTimeoutException -> R.string.socket_timeout
else -> {R.string.unknown}
}
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
is Result.Success -> view.populate(it.data)
}
}.launchIn(lifecycleScope)
}
}
6 changes: 6 additions & 0 deletions flowcats/src/main/java/otus/homework/flowcats/Result.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package otus.homework.flowcats

sealed interface Result<out D> {
data class Success<out D>(val data: D) : Result<D>
data class Error<D>(val error: Throwable) : Result<D>
}
2 changes: 2 additions & 0 deletions flowcats/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<resources>
<string name="app_name">Flow cats</string>
<string name="socket_timeout">Не удалось получить ответ от сервера</string>
<string name="unknown">Неизвестная ошибка</string>
</resources>
23 changes: 19 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,8 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers().map { it * 5 }
.filterNot { it <= 20 || it % 2 == 0 }.map { "$it won" }.take(3)
}

/**
Expand All @@ -29,7 +30,14 @@ class SampleInteractor(
* Если число не делится на 3,5,15 - эмитим само число
*/
fun task2(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers().flatMapConcat { num ->
when {
num % 15 == 0 -> flowOf("$num", "FizzBuzz")
num % 3 == 0 -> flowOf("$num", "Fizz")
num % 5 == 0 -> flowOf("$num", "Buzz")
else -> flowOf("$num")
}
}
}

/**
Expand All @@ -38,7 +46,9 @@ 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 +58,11 @@ class SampleInteractor(
* При любом исходе, будь то выброс исключения или успешная отработка функции вызовите метод dotsRepository.completed()
*/
fun task4(): Flow<Int> {
return flowOf()
return sampleRepository.produceNumbers()
.catch { cause: Throwable ->
if (cause is IllegalArgumentException) emit(-1)
else throw cause
}
.onCompletion { sampleRepository.completed() }
}
}