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
2 changes: 2 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,6 @@ dependencies {
implementation 'com.google.android.material:material:1.11.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3'
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
}
6 changes: 6 additions & 0 deletions app/src/main/java/otus/homework/coroutines/CatDataModel.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package otus.homework.coroutines

data class CatDataModel(
val fact: Fact,
val imageUrl: String?
)
42 changes: 28 additions & 14 deletions app/src/main/java/otus/homework/coroutines/CatsPresenter.kt
Original file line number Diff line number Diff line change
@@ -1,35 +1,49 @@
package otus.homework.coroutines

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlinx.coroutines.*
import otus.homework.coroutines.CrashMonitor.trackWarning
import java.net.SocketTimeoutException

class CatsPresenter(
private val catsService: CatsService
private val catsService: CatsService,
private val imageService: ImageService,
) {

private var _catsView: ICatsView? = null
private val scopeCats = CoroutineScope(Dispatchers.Main + CoroutineName("CatsCoroutine"))


fun onInitComplete() {
catsService.getCatFact().enqueue(object : Callback<Fact> {

override fun onResponse(call: Call<Fact>, response: Response<Fact>) {
if (response.isSuccessful && response.body() != null) {
_catsView?.populate(response.body()!!)
}
}
scopeCats.launch {
try {
val responseFact = async {catsService.getCatFact()}
val responseImage = async {imageService.getImage().firstOrNull()}

_catsView?.populate(CatDataModel(responseFact.await(), responseImage.await()?.url))


override fun onFailure(call: Call<Fact>, t: Throwable) {
CrashMonitor.trackWarning()
} catch (e: SocketTimeoutException) {
val error = e.message ?: "Не удалось получить ответ от сервера"
_catsView?.showToast(error)
} catch (e: Exception) {
val errorMessage = e.message ?: "Unknown error"
trackWarning(errorMessage)
_catsView?.showToast(errorMessage)
}
})
}
}


fun attachView(catsView: ICatsView) {
_catsView = catsView
}

fun detachView() {
_catsView = null
}
}

fun onStop() {
scopeCats.cancel()
}
}
5 changes: 2 additions & 3 deletions app/src/main/java/otus/homework/coroutines/CatsService.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package otus.homework.coroutines

import retrofit2.Call
import retrofit2.http.GET

interface CatsService {

@GET("fact")
fun getCatFact() : Call<Fact>
}
suspend fun getCatFact() : Fact
}
24 changes: 20 additions & 4 deletions app/src/main/java/otus/homework/coroutines/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import android.content.Context
import android.util.AttributeSet
import android.widget.Button
import android.widget.TextView
import android.widget.ImageView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import com.squareup.picasso.Picasso

class CatsView @JvmOverloads constructor(
context: Context,
Expand All @@ -13,20 +16,33 @@ class CatsView @JvmOverloads constructor(
) : ConstraintLayout(context, attrs, defStyleAttr), ICatsView {

var presenter :CatsPresenter? = null
var viewModel: CatsViewModel? = null

override fun onFinishInflate() {
super.onFinishInflate()
findViewById<Button>(R.id.button).setOnClickListener {
presenter?.onInitComplete()
if (presenter != null) {
presenter?.onInitComplete()
} else {
viewModel?.onInitComplete()
}
}
}

override fun populate(fact: Fact) {
findViewById<TextView>(R.id.fact_textView).text = fact.fact
override fun populate(data: CatDataModel) {
findViewById<TextView>(R.id.fact_textView).text = data.fact.fact
val imageView = findViewById<ImageView>(R.id.imageContainer)
Picasso.get().load(data.imageUrl).into(imageView)
}

override fun showToast(message: String?) {
Toast.makeText(context, message ?: "Неизвестная ошибка", Toast.LENGTH_LONG).show()
}
}

interface ICatsView {

fun populate(fact: Fact)
}
fun populate(data: CatDataModel)
fun showToast(message: String?)
}
42 changes: 42 additions & 0 deletions app/src/main/java/otus/homework/coroutines/CatsViewModel.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package otus.homework.coroutines

import kotlinx.coroutines.*
import otus.homework.coroutines.CrashMonitor.trackWarning
import java.net.SocketTimeoutException
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow


class CatsViewModel(
private val catsService: CatsService,
private val imageService: ImageService,
private val onShowToast: (String?) -> Unit
) : ViewModel() {

private val _state = MutableStateFlow<Result>(Result.Error("No fact found"))

private val handler = CoroutineExceptionHandler { _, exception ->
if(exception is SocketTimeoutException){
onShowToast("Не удалось получить ответ от сервера")
}else {
trackWarning("CoroutineExceptionHandler got $exception")
onShowToast(exception.message)
}
_state.value = Result.Error(exception.message)
}

fun onInitComplete() {
viewModelScope.launch (handler){
val fact = async { catsService.getCatFact() }
val image = async { imageService.getImage().firstOrNull() }
val model = CatDataModel(fact.await(), image.await()?.url)
_state.value = Result.Success(model)
}
}
}

sealed class Result {
data class Success<T>(val data: T) : Result()
data class Error(val msg: String?) : Result()
}
3 changes: 2 additions & 1 deletion app/src/main/java/otus/homework/coroutines/CrashMonitor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ object CrashMonitor {
/**
* Pretend this is Crashlytics/AppCenter
*/
fun trackWarning() {
fun trackWarning(message: String?) {
println("CrashMonitor: $message")
}
}
11 changes: 10 additions & 1 deletion app/src/main/java/otus/homework/coroutines/DiContainer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,14 @@ class DiContainer {
.build()
}

private val retrofitImage by lazy {
Retrofit.Builder()
.baseUrl("https://api.thecatapi.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}

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

val serviceImage by lazy { retrofitImage.create(ImageService::class.java) }
}
15 changes: 15 additions & 0 deletions app/src/main/java/otus/homework/coroutines/Image.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package otus.homework.coroutines

import com.google.gson.annotations.SerializedName

data class Image(
@field:SerializedName("id")
val id: String,
@field:SerializedName("url")
val url: String,
@field:SerializedName("width")
val width: Int,
@field:SerializedName("height")
val height: Int

)
9 changes: 9 additions & 0 deletions app/src/main/java/otus/homework/coroutines/ImageService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package otus.homework.coroutines

import retrofit2.http.GET

interface ImageService {

@GET ("v1/images/search")
suspend fun getImage() : List<Image>
}
6 changes: 5 additions & 1 deletion app/src/main/java/otus/homework/coroutines/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ class MainActivity : AppCompatActivity() {
val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView
setContentView(view)

catsPresenter = CatsPresenter(diContainer.service)
catsPresenter = CatsPresenter(
diContainer.service,
imageService = diContainer.serviceImage
)
view.presenter = catsPresenter
catsPresenter.attachView(view)
catsPresenter.onInitComplete()
Expand All @@ -24,6 +27,7 @@ class MainActivity : AppCompatActivity() {
override fun onStop() {
if (isFinishing) {
catsPresenter.detachView()
catsPresenter.onStop()
}
super.onStop()
}
Expand Down
18 changes: 14 additions & 4 deletions app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,28 @@
android:textSize="24sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
app:layout_constraintTop_toBottomOf="@+id/fact_textView"
android:id="@+id/imageContainer"
android:layout_width="342dp"
android:layout_height="257dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />


<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_width="148dp"
android:layout_height="51dp"
android:text="@string/more_facts"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/fact_textView" />
app:layout_constraintTop_toBottomOf="@+id/imageContainer" />

</otus.homework.coroutines.CatsView>