From 0324475f00a49c7bef6ba22030f5f34ab7fec8fe Mon Sep 17 00:00:00 2001 From: nikolayNazarov Date: Thu, 6 Feb 2025 23:04:35 +0300 Subject: [PATCH 01/10] 3 done --- .../otus/homework/coroutines/CatsPresenter.kt | 38 ++++++++++++++----- .../otus/homework/coroutines/CatsService.kt | 3 +- .../homework/coroutines/PresenterScope.kt | 16 ++++++++ 3 files changed, 46 insertions(+), 11 deletions(-) create mode 100644 app/src/main/java/otus/homework/coroutines/PresenterScope.kt diff --git a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt index e4b05120..18481223 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt @@ -1,5 +1,9 @@ package otus.homework.coroutines +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import retrofit2.Call import retrofit2.Callback import retrofit2.Response @@ -9,20 +13,35 @@ class CatsPresenter( ) { private var _catsView: ICatsView? = null + private val presenterScope = PresenterScope() fun onInitComplete() { - catsService.getCatFact().enqueue(object : Callback { - - override fun onResponse(call: Call, response: Response) { - if (response.isSuccessful && response.body() != null) { - _catsView?.populate(response.body()!!) + presenterScope.launch { + try { + // Переходим к фоновому потоку для выполнения запроса + val fact = withContext(Dispatchers.IO) { + catsService.getCatFact() } - } - - override fun onFailure(call: Call, t: Throwable) { + // Добавляем факт + _catsView?.populate(fact) + } catch (e: Exception) { + // Обрабатываем ошибку, если необходимо CrashMonitor.trackWarning() + } - }) + } +// catsService.getCatFact()(object : Callback { +// +// override fun onResponse(call: Call, response: Response) { +// if (response.isSuccessful && response.body() != null) { +// _catsView?.populate(response.body()!!) +// } +// } +// +// override fun onFailure(call: Call, t: Throwable) { +// CrashMonitor.trackWarning() +// } +// }) } fun attachView(catsView: ICatsView) { @@ -31,5 +50,6 @@ class CatsPresenter( fun detachView() { _catsView = null + presenterScope.clear() } } \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/CatsService.kt b/app/src/main/java/otus/homework/coroutines/CatsService.kt index 479b2cfb..db865d0c 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsService.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsService.kt @@ -1,10 +1,9 @@ package otus.homework.coroutines -import retrofit2.Call import retrofit2.http.GET interface CatsService { @GET("fact") - fun getCatFact() : Call + suspend fun getCatFact() : Fact } \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/PresenterScope.kt b/app/src/main/java/otus/homework/coroutines/PresenterScope.kt new file mode 100644 index 00000000..0392fdf6 --- /dev/null +++ b/app/src/main/java/otus/homework/coroutines/PresenterScope.kt @@ -0,0 +1,16 @@ +package otus.homework.coroutines + +import kotlinx.coroutines.CoroutineName +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.CoroutineScope + +class PresenterScope : CoroutineScope { + private val job = Job() + + override val coroutineContext = job + Dispatchers.Main + CoroutineName("CatsCoroutine") + + fun clear() { + job.cancel() + } +} From 41861c4056eabdd9cbd7eb69ac7f18db23161273 Mon Sep 17 00:00:00 2001 From: nikolayNazarov Date: Thu, 6 Feb 2025 23:14:58 +0300 Subject: [PATCH 02/10] 1.5 done --- .../otus/homework/coroutines/CatsPresenter.kt | 40 +++++++++---------- .../otus/homework/coroutines/CrashMonitor.kt | 2 +- .../otus/homework/coroutines/MainActivity.kt | 2 +- 3 files changed, 20 insertions(+), 24 deletions(-) diff --git a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt index 18481223..76f4ba5d 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt @@ -1,15 +1,15 @@ package otus.homework.coroutines -import kotlinx.coroutines.CoroutineScope +import android.content.Context +import android.widget.Toast import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -import retrofit2.Call -import retrofit2.Callback -import retrofit2.Response +import java.net.SocketTimeoutException class CatsPresenter( - private val catsService: CatsService + private val catsService: CatsService, + private val context: Context // Для показа Toast ) { private var _catsView: ICatsView? = null @@ -25,23 +25,19 @@ class CatsPresenter( // Добавляем факт _catsView?.populate(fact) } catch (e: Exception) { - // Обрабатываем ошибку, если необходимо - CrashMonitor.trackWarning() - + when (e) { + is SocketTimeoutException -> { + // Показываем Toast для таймаута + Toast.makeText(context, "Не удалось получить ответ от сервером", Toast.LENGTH_SHORT).show() + } + else -> { + // Логируем исключение и показываем сообщение для остальных случаев + CrashMonitor.trackWarning(e) + Toast.makeText(context, e.message ?: "Произошла ошибка", Toast.LENGTH_SHORT).show() + } + } } } -// catsService.getCatFact()(object : Callback { -// -// override fun onResponse(call: Call, response: Response) { -// if (response.isSuccessful && response.body() != null) { -// _catsView?.populate(response.body()!!) -// } -// } -// -// override fun onFailure(call: Call, t: Throwable) { -// CrashMonitor.trackWarning() -// } -// }) } fun attachView(catsView: ICatsView) { @@ -50,6 +46,6 @@ class CatsPresenter( fun detachView() { _catsView = null - presenterScope.clear() + } -} \ No newline at end of file +} diff --git a/app/src/main/java/otus/homework/coroutines/CrashMonitor.kt b/app/src/main/java/otus/homework/coroutines/CrashMonitor.kt index 32e6b018..9beb665d 100644 --- a/app/src/main/java/otus/homework/coroutines/CrashMonitor.kt +++ b/app/src/main/java/otus/homework/coroutines/CrashMonitor.kt @@ -5,6 +5,6 @@ object CrashMonitor { /** * Pretend this is Crashlytics/AppCenter */ - fun trackWarning() { + fun trackWarning(e: Exception) { } } \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/MainActivity.kt b/app/src/main/java/otus/homework/coroutines/MainActivity.kt index a9dafb3b..d52f1372 100644 --- a/app/src/main/java/otus/homework/coroutines/MainActivity.kt +++ b/app/src/main/java/otus/homework/coroutines/MainActivity.kt @@ -15,7 +15,7 @@ class MainActivity : AppCompatActivity() { val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView setContentView(view) - catsPresenter = CatsPresenter(diContainer.service) + catsPresenter = CatsPresenter(diContainer.service, this) view.presenter = catsPresenter catsPresenter.attachView(view) catsPresenter.onInitComplete() From 8764927eeb78d1b97a811373fe1499436aad04d9 Mon Sep 17 00:00:00 2001 From: nikolayNazarov Date: Sun, 9 Feb 2025 21:29:08 +0300 Subject: [PATCH 03/10] 1.5 done --- app/src/main/java/otus/homework/coroutines/CatsPresenter.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt index 76f4ba5d..3d4f3dfe 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt @@ -46,6 +46,7 @@ class CatsPresenter( fun detachView() { _catsView = null + presenterScope.clear() } } From ee3245e4e6002ed5edd9332d3bc09df3a7ee7223 Mon Sep 17 00:00:00 2001 From: nikolayNazarov Date: Sun, 9 Feb 2025 21:55:06 +0300 Subject: [PATCH 04/10] 2.1 half --- .../main/java/otus/homework/coroutines/CatImage.kt | 14 ++++++++++++++ .../otus/homework/coroutines/CatsImagesService.kt | 8 ++++++++ .../java/otus/homework/coroutines/DiContainer.kt | 13 +++++++++++-- .../java/otus/homework/coroutines/MainActivity.kt | 2 +- app/src/main/res/layout/activity_main.xml | 9 +++++++++ 5 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 app/src/main/java/otus/homework/coroutines/CatImage.kt create mode 100644 app/src/main/java/otus/homework/coroutines/CatsImagesService.kt diff --git a/app/src/main/java/otus/homework/coroutines/CatImage.kt b/app/src/main/java/otus/homework/coroutines/CatImage.kt new file mode 100644 index 00000000..bf902810 --- /dev/null +++ b/app/src/main/java/otus/homework/coroutines/CatImage.kt @@ -0,0 +1,14 @@ +package otus.homework.coroutines + +import com.google.gson.annotations.SerializedName + +data class CatImage( + @field:SerializedName("id") + val id: String, + @field:SerializedName("url") + val url: String, + @field:SerializedName("width") + val width: String, + @field:SerializedName("height") + val height: String +) \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/CatsImagesService.kt b/app/src/main/java/otus/homework/coroutines/CatsImagesService.kt new file mode 100644 index 00000000..8d282317 --- /dev/null +++ b/app/src/main/java/otus/homework/coroutines/CatsImagesService.kt @@ -0,0 +1,8 @@ +package otus.homework.coroutines + +import retrofit2.http.GET + +interface CatImagesService { + @GET("images/search") + suspend fun getCatImage(): List +} \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/DiContainer.kt b/app/src/main/java/otus/homework/coroutines/DiContainer.kt index 23ddc3b2..8f035d44 100644 --- a/app/src/main/java/otus/homework/coroutines/DiContainer.kt +++ b/app/src/main/java/otus/homework/coroutines/DiContainer.kt @@ -5,12 +5,21 @@ import retrofit2.converter.gson.GsonConverterFactory class DiContainer { - private val retrofit by lazy { + private val retrofitCatFacts by lazy { Retrofit.Builder() .baseUrl("https://catfact.ninja/") .addConverterFactory(GsonConverterFactory.create()) .build() } - val service by lazy { retrofit.create(CatsService::class.java) } + val catFactsService by lazy { retrofitCatFacts.create(CatsService::class.java) } + + private val retrofitCatImagesSource by lazy { + Retrofit.Builder() + .baseUrl("https://api.thecatapi.com/v1/images/search") + .addConverterFactory(GsonConverterFactory.create()) + .build() + } + + val catImagesSourceService by lazy { retrofitCatImagesSource.create(CatsService::class.java) } } \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/MainActivity.kt b/app/src/main/java/otus/homework/coroutines/MainActivity.kt index d52f1372..e7ed127f 100644 --- a/app/src/main/java/otus/homework/coroutines/MainActivity.kt +++ b/app/src/main/java/otus/homework/coroutines/MainActivity.kt @@ -15,7 +15,7 @@ class MainActivity : AppCompatActivity() { val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView setContentView(view) - catsPresenter = CatsPresenter(diContainer.service, this) + catsPresenter = CatsPresenter(diContainer.catFactsService, this) view.presenter = catsPresenter catsPresenter.attachView(view) catsPresenter.onInitComplete() diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 9508066d..b4931406 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -7,6 +7,15 @@ android:layout_height="match_parent" tools:context=".MainActivity"> + + Date: Sun, 9 Feb 2025 23:03:44 +0300 Subject: [PATCH 05/10] 2.1 half --- app/src/main/java/otus/homework/coroutines/CatsView.kt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/otus/homework/coroutines/CatsView.kt b/app/src/main/java/otus/homework/coroutines/CatsView.kt index be04b2a8..e8d56c76 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsView.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsView.kt @@ -3,6 +3,7 @@ package otus.homework.coroutines import android.content.Context import android.util.AttributeSet import android.widget.Button +import android.widget.ImageView import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout @@ -24,9 +25,13 @@ class CatsView @JvmOverloads constructor( override fun populate(fact: Fact) { findViewById(R.id.fact_textView).text = fact.fact } + + override fun showCatImage() { + findViewById(R.id.cat_fact_imageView) + } } interface ICatsView { - fun populate(fact: Fact) + fun showCatImage() } \ No newline at end of file From 96e4b1700ff59d6e7621085acae1b607fd275da5 Mon Sep 17 00:00:00 2001 From: nikolayNazarov Date: Sun, 9 Feb 2025 23:50:18 +0300 Subject: [PATCH 06/10] 2.1 done --- .../homework/coroutines/CatsImagesService.kt | 2 +- .../otus/homework/coroutines/CatsPresenter.kt | 68 +++++++++++++------ .../otus/homework/coroutines/CatsService.kt | 1 - .../java/otus/homework/coroutines/CatsView.kt | 15 +++- .../otus/homework/coroutines/DiContainer.kt | 4 +- .../otus/homework/coroutines/MainActivity.kt | 2 +- app/src/main/res/layout/activity_main.xml | 4 +- 7 files changed, 66 insertions(+), 30 deletions(-) diff --git a/app/src/main/java/otus/homework/coroutines/CatsImagesService.kt b/app/src/main/java/otus/homework/coroutines/CatsImagesService.kt index 8d282317..0cb75d5b 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsImagesService.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsImagesService.kt @@ -3,6 +3,6 @@ package otus.homework.coroutines import retrofit2.http.GET interface CatImagesService { - @GET("images/search") + @GET("v1/images/search/") suspend fun getCatImage(): List } \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt index 3d4f3dfe..7d83860f 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt @@ -1,6 +1,7 @@ package otus.homework.coroutines import android.content.Context +import android.util.Log import android.widget.Toast import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -9,6 +10,7 @@ import java.net.SocketTimeoutException class CatsPresenter( private val catsService: CatsService, + private val catImagesService: CatImagesService, private val context: Context // Для показа Toast ) { @@ -17,26 +19,8 @@ class CatsPresenter( fun onInitComplete() { presenterScope.launch { - try { - // Переходим к фоновому потоку для выполнения запроса - val fact = withContext(Dispatchers.IO) { - catsService.getCatFact() - } - // Добавляем факт - _catsView?.populate(fact) - } catch (e: Exception) { - when (e) { - is SocketTimeoutException -> { - // Показываем Toast для таймаута - Toast.makeText(context, "Не удалось получить ответ от сервером", Toast.LENGTH_SHORT).show() - } - else -> { - // Логируем исключение и показываем сообщение для остальных случаев - CrashMonitor.trackWarning(e) - Toast.makeText(context, e.message ?: "Произошла ошибка", Toast.LENGTH_SHORT).show() - } - } - } + loadCatFact() + loadCatImage() } } @@ -49,4 +33,48 @@ class CatsPresenter( presenterScope.clear() } + + private suspend fun loadCatFact() { + try { + // Переходим к фоновому потоку для выполнения запроса + val fact = withContext(Dispatchers.IO) { + catsService.getCatFact() + } + // Добавляем факт + _catsView?.populate(fact) + } catch (e: Exception) { + when (e) { + is SocketTimeoutException -> { + // Показываем Toast для таймаута + Toast.makeText( + context, + "Не удалось получить ответ от сервером", + Toast.LENGTH_SHORT + ).show() + } + + else -> { + // Логируем исключение и показываем сообщение для остальных случаев + CrashMonitor.trackWarning(e) + Toast.makeText(context, e.message ?: "Произошла ошибка", Toast.LENGTH_SHORT) + .show() + } + } + } + } + + private suspend fun loadCatImage() { + Log.i("debug", "Pfuheprf") + val catImageList = catImagesService.getCatImage() + val imageUrl = catImageList.firstOrNull()?.url // Получение URL, если существует + + // Отрисовка изображения в UI-потоке + if (imageUrl != null) { + _catsView?.showCatImage(imageUrl) // Вызов метода для отображения изображения + } else { + // Обработайте ситуацию, когда URL не найден + Toast.makeText(context, "Изображение не найдено", Toast.LENGTH_SHORT).show() + } + } } + diff --git a/app/src/main/java/otus/homework/coroutines/CatsService.kt b/app/src/main/java/otus/homework/coroutines/CatsService.kt index db865d0c..94c1ae9d 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsService.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsService.kt @@ -3,7 +3,6 @@ package otus.homework.coroutines import retrofit2.http.GET interface CatsService { - @GET("fact") suspend fun getCatFact() : Fact } \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/CatsView.kt b/app/src/main/java/otus/homework/coroutines/CatsView.kt index e8d56c76..7f358e1b 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsView.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsView.kt @@ -2,10 +2,12 @@ package otus.homework.coroutines import android.content.Context import android.util.AttributeSet +import android.util.Log import android.widget.Button import android.widget.ImageView import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout +import com.squareup.picasso.Picasso class CatsView @JvmOverloads constructor( context: Context, @@ -26,12 +28,19 @@ class CatsView @JvmOverloads constructor( findViewById(R.id.fact_textView).text = fact.fact } - override fun showCatImage() { - findViewById(R.id.cat_fact_imageView) + override fun showCatImage(imageUrl: String) { + val imageView: ImageView = findViewById(R.id.cat_fact_imageView) + Log.i("debug", "url = $imageUrl") + // Загружаем изображение с помощью Picasso + Picasso.get() + .load(imageUrl) + .into(imageView) } + + } interface ICatsView { fun populate(fact: Fact) - fun showCatImage() + fun showCatImage(imageUrl: String) } \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/DiContainer.kt b/app/src/main/java/otus/homework/coroutines/DiContainer.kt index 8f035d44..1c7bd7ca 100644 --- a/app/src/main/java/otus/homework/coroutines/DiContainer.kt +++ b/app/src/main/java/otus/homework/coroutines/DiContainer.kt @@ -16,10 +16,10 @@ class DiContainer { private val retrofitCatImagesSource by lazy { Retrofit.Builder() - .baseUrl("https://api.thecatapi.com/v1/images/search") + .baseUrl("https://api.thecatapi.com/") .addConverterFactory(GsonConverterFactory.create()) .build() } - val catImagesSourceService by lazy { retrofitCatImagesSource.create(CatsService::class.java) } + val catImagesSourceService by lazy { retrofitCatImagesSource.create(CatImagesService::class.java) } } \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/MainActivity.kt b/app/src/main/java/otus/homework/coroutines/MainActivity.kt index e7ed127f..8d17466b 100644 --- a/app/src/main/java/otus/homework/coroutines/MainActivity.kt +++ b/app/src/main/java/otus/homework/coroutines/MainActivity.kt @@ -15,7 +15,7 @@ class MainActivity : AppCompatActivity() { val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView setContentView(view) - catsPresenter = CatsPresenter(diContainer.catFactsService, this) + catsPresenter = CatsPresenter(diContainer.catFactsService, diContainer.catImagesSourceService,this) view.presenter = catsPresenter catsPresenter.attachView(view) catsPresenter.onInitComplete() diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index b4931406..28ccab9b 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -9,8 +9,8 @@ Date: Mon, 10 Feb 2025 00:14:42 +0300 Subject: [PATCH 07/10] 2.3 done --- .../coroutines/CatPresentationModel.kt | 6 ++ .../otus/homework/coroutines/CatsPresenter.kt | 67 +++++++++---------- .../java/otus/homework/coroutines/CatsView.kt | 17 ++--- 3 files changed, 43 insertions(+), 47 deletions(-) create mode 100644 app/src/main/java/otus/homework/coroutines/CatPresentationModel.kt diff --git a/app/src/main/java/otus/homework/coroutines/CatPresentationModel.kt b/app/src/main/java/otus/homework/coroutines/CatPresentationModel.kt new file mode 100644 index 00000000..f46594d9 --- /dev/null +++ b/app/src/main/java/otus/homework/coroutines/CatPresentationModel.kt @@ -0,0 +1,6 @@ +package otus.homework.coroutines + +data class CatPresentationModel( + val fact: String, + val imageUrl: String +) diff --git a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt index 7d83860f..619b5cb7 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt @@ -19,8 +19,17 @@ class CatsPresenter( fun onInitComplete() { presenterScope.launch { - loadCatFact() - loadCatImage() + try { + val fact = loadCatFact() + val imageUrl = loadCatImage() + + if (fact != null && imageUrl != null) { + val catModel = CatPresentationModel(fact.fact, imageUrl) + _catsView?.populate(catModel) + } + } catch (e: Exception) { + handleException(e) + } } } @@ -34,46 +43,30 @@ class CatsPresenter( } - private suspend fun loadCatFact() { - try { - // Переходим к фоновому потоку для выполнения запроса - val fact = withContext(Dispatchers.IO) { - catsService.getCatFact() - } - // Добавляем факт - _catsView?.populate(fact) - } catch (e: Exception) { - when (e) { - is SocketTimeoutException -> { - // Показываем Toast для таймаута - Toast.makeText( - context, - "Не удалось получить ответ от сервером", - Toast.LENGTH_SHORT - ).show() - } + private suspend fun loadCatFact(): Fact? { + return withContext(Dispatchers.IO) { + catsService.getCatFact() + } + } - else -> { - // Логируем исключение и показываем сообщение для остальных случаев - CrashMonitor.trackWarning(e) - Toast.makeText(context, e.message ?: "Произошла ошибка", Toast.LENGTH_SHORT) - .show() - } - } + private suspend fun loadCatImage(): String? { + return withContext(Dispatchers.IO) { + val catImageList = catImagesService.getCatImage() + catImageList.firstOrNull()?.url // Возвращаем URL, если существует } } - private suspend fun loadCatImage() { - Log.i("debug", "Pfuheprf") - val catImageList = catImagesService.getCatImage() - val imageUrl = catImageList.firstOrNull()?.url // Получение URL, если существует + private fun handleException(e: Exception) { + when (e) { + is SocketTimeoutException -> { + Toast.makeText(context, "Не удалось получить ответ от сервером", Toast.LENGTH_SHORT) + .show() + } - // Отрисовка изображения в UI-потоке - if (imageUrl != null) { - _catsView?.showCatImage(imageUrl) // Вызов метода для отображения изображения - } else { - // Обработайте ситуацию, когда URL не найден - Toast.makeText(context, "Изображение не найдено", Toast.LENGTH_SHORT).show() + else -> { + CrashMonitor.trackWarning(e) + Toast.makeText(context, e.message ?: "Произошла ошибка", Toast.LENGTH_SHORT).show() + } } } } diff --git a/app/src/main/java/otus/homework/coroutines/CatsView.kt b/app/src/main/java/otus/homework/coroutines/CatsView.kt index 7f358e1b..be5843f2 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsView.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsView.kt @@ -24,23 +24,20 @@ class CatsView @JvmOverloads constructor( } } - override fun populate(fact: Fact) { - findViewById(R.id.fact_textView).text = fact.fact + override fun populate(catModel: CatPresentationModel) { + findViewById(R.id.fact_textView).text = catModel.fact + showCatImage(catModel.imageUrl) } - override fun showCatImage(imageUrl: String) { + private fun showCatImage(imageUrl: String) { val imageView: ImageView = findViewById(R.id.cat_fact_imageView) - Log.i("debug", "url = $imageUrl") - // Загружаем изображение с помощью Picasso - Picasso.get() - .load(imageUrl) - .into(imageView) + Picasso.get().load(imageUrl).into(imageView) } + } interface ICatsView { - fun populate(fact: Fact) - fun showCatImage(imageUrl: String) + fun populate(catModel: CatPresentationModel) } \ No newline at end of file From 138192e494f24cb76ff2e70c572e4f2e80871c79 Mon Sep 17 00:00:00 2001 From: nikolayNazarov Date: Mon, 10 Feb 2025 00:53:07 +0300 Subject: [PATCH 08/10] 3 done --- app/build.gradle | 3 ++ .../otus/homework/coroutines/CatsPresenter.kt | 54 ------------------- .../java/otus/homework/coroutines/CatsView.kt | 29 +++++----- .../otus/homework/coroutines/CatsViewModel.kt | 53 ++++++++++++++++++ .../otus/homework/coroutines/MainActivity.kt | 37 ++++++++----- .../java/otus/homework/coroutines/Result.kt | 6 +++ 6 files changed, 102 insertions(+), 80 deletions(-) create mode 100644 app/src/main/java/otus/homework/coroutines/CatsViewModel.kt create mode 100644 app/src/main/java/otus/homework/coroutines/Result.kt diff --git a/app/build.gradle b/app/build.gradle index a414e0e8..54c1337f 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -41,4 +41,7 @@ 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 "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0" + implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.4.0" } \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt index 619b5cb7..68df5fc1 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt @@ -14,60 +14,6 @@ class CatsPresenter( private val context: Context // Для показа Toast ) { - private var _catsView: ICatsView? = null - private val presenterScope = PresenterScope() - fun onInitComplete() { - presenterScope.launch { - try { - val fact = loadCatFact() - val imageUrl = loadCatImage() - - if (fact != null && imageUrl != null) { - val catModel = CatPresentationModel(fact.fact, imageUrl) - _catsView?.populate(catModel) - } - } catch (e: Exception) { - handleException(e) - } - } - } - - fun attachView(catsView: ICatsView) { - _catsView = catsView - } - - fun detachView() { - _catsView = null - presenterScope.clear() - - } - - private suspend fun loadCatFact(): Fact? { - return withContext(Dispatchers.IO) { - catsService.getCatFact() - } - } - - private suspend fun loadCatImage(): String? { - return withContext(Dispatchers.IO) { - val catImageList = catImagesService.getCatImage() - catImageList.firstOrNull()?.url // Возвращаем URL, если существует - } - } - - private fun handleException(e: Exception) { - when (e) { - is SocketTimeoutException -> { - Toast.makeText(context, "Не удалось получить ответ от сервером", Toast.LENGTH_SHORT) - .show() - } - - else -> { - CrashMonitor.trackWarning(e) - Toast.makeText(context, e.message ?: "Произошла ошибка", Toast.LENGTH_SHORT).show() - } - } - } } diff --git a/app/src/main/java/otus/homework/coroutines/CatsView.kt b/app/src/main/java/otus/homework/coroutines/CatsView.kt index be5843f2..66df9bd2 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsView.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsView.kt @@ -2,10 +2,10 @@ package otus.homework.coroutines import android.content.Context import android.util.AttributeSet -import android.util.Log import android.widget.Button import android.widget.ImageView import android.widget.TextView +import android.widget.Toast import androidx.constraintlayout.widget.ConstraintLayout import com.squareup.picasso.Picasso @@ -13,18 +13,30 @@ class CatsView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 -) : ConstraintLayout(context, attrs, defStyleAttr), ICatsView { +) : ConstraintLayout(context, attrs, defStyleAttr) { - var presenter :CatsPresenter? = null + private lateinit var viewModel: CatsViewModel override fun onFinishInflate() { super.onFinishInflate() findViewById