Skip to content
Open

Hw3 #228

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
6 changes: 3 additions & 3 deletions flowcats/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ plugins {
}

android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
compileSdk 34
buildToolsVersion "34.0.0"

namespace = "otus.homework.flowcats"

defaultConfig {
applicationId "otus.homework.flowcats"
minSdkVersion 23
targetSdkVersion 30
targetSdkVersion 33
versionCode 1
versionName "1.0"

Expand Down
3 changes: 2 additions & 1 deletion flowcats/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Flow" >
<activity android:name=".MainActivity">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package otus.homework.flowcats

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn


class CatsRepository(
private val catsService: CatsService,
Expand All @@ -11,8 +14,8 @@ class CatsRepository(
fun listenForCatFacts() = flow {
while (true) {
val latestNews = catsService.getCatFact()
emit(latestNews)
delay(refreshIntervalMs)
emit (latestNews)
delay (refreshIntervalMs)
}
}
}.flowOn(Dispatchers.IO)
}
5 changes: 3 additions & 2 deletions flowcats/src/main/java/otus/homework/flowcats/CatsService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import retrofit2.http.GET

interface CatsService {

@GET("random?animal_type=cat")
suspend fun getCatFact(): Fact
// @GET("random?animal_type=cat")
@GET("fact")
suspend fun getCatFact(): Fact
}
15 changes: 14 additions & 1 deletion flowcats/src/main/java/otus/homework/flowcats/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,33 @@ package otus.homework.flowcats
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout


class CatsView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : 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
}

override fun showError(message: String?) {
Toast.makeText(context, message ?: context.getText(R.string.error), Toast.LENGTH_LONG)
.show()
}

override fun load() {
findViewById<TextView>(R.id.fact_textView).text = context.getText(R.string.loading)
}
}

interface ICatsView {

fun populate(fact: Fact)
fun showError(message: String?)
fun load()
}
37 changes: 22 additions & 15 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,31 +1,38 @@
package otus.homework.flowcats

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


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

private val _catsLiveData = MutableLiveData<Fact>()
val catsLiveData: LiveData<Fact> = _catsLiveData
private val _catsFlow = MutableStateFlow<Result>(Result.Initial)
val catsFlow: StateFlow<Result> = _catsFlow.asStateFlow()

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
// viewModelScope.launch {
catsRepository.listenForCatFacts()
.onEach {_catsFlow.value = Result.Success(it)}
.catch { _catsFlow.value = Result.Error(it.message.toString()) }
.launchIn(viewModelScope)

}
}
}
}
}





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

private val retrofit by lazy {
Retrofit.Builder()
.baseUrl("https://cat-fact.herokuapp.com/facts/")
.baseUrl("https://catfact.ninja/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}

val service by lazy { retrofit.create(CatsService::class.java) }
val service: CatsService by lazy { retrofit.create(CatsService::class.java) }

val repository by lazy { CatsRepository(service) }
}
40 changes: 22 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,26 @@ 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("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
)
17 changes: 13 additions & 4 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,28 @@ package otus.homework.flowcats
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach


class MainActivity : AppCompatActivity() {

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

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)
}
catsViewModel.catsFlow.onEach{
when (it) {
is Result.Initial -> view.load()
is Result.Success -> {view.populate(it.fact)}
is Result.Error -> view.showError(it.errorMsg)
}
}.launchIn(lifecycleScope)
}
}
7 changes: 7 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,7 @@
package otus.homework.flowcats

sealed class Result {
data class Success(val fact: Fact) : Result()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

по условиям задачи должен быть дженерик Success<T>

data class Error(val errorMsg: String?) : Result()
data object Initial: Result()
}
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="error">Error</string>
<string name="loading">Loading…</string>
</resources>
31 changes: 27 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,16 @@ 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 +52,10 @@ class SampleInteractor(
* Если айтемы в одно из флоу кончились то результирующий флоу также должен закончится
*/
fun task3(): Flow<Pair<String, String>> {
return flowOf()
return sampleRepository.produceColors()
.zip(sampleRepository.produceForms()) { color, form ->
Pair(color, form)
}
}

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