diff --git a/app/build.gradle b/app/build.gradle index a414e0e8..f61d978f 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -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 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.3' + implementation 'androidx.fragment:fragment-ktx:1.8.1' } \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/Cat.kt b/app/src/main/java/otus/homework/coroutines/Cat.kt new file mode 100644 index 00000000..82063859 --- /dev/null +++ b/app/src/main/java/otus/homework/coroutines/Cat.kt @@ -0,0 +1,6 @@ +package otus.homework.coroutines + +data class Cat( + val fact: String, + val imageUrl: String +) \ 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/CatFactService.kt similarity index 50% rename from app/src/main/java/otus/homework/coroutines/CatsService.kt rename to app/src/main/java/otus/homework/coroutines/CatFactService.kt index 479b2cfb..617b198f 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsService.kt +++ b/app/src/main/java/otus/homework/coroutines/CatFactService.kt @@ -1,10 +1,9 @@ package otus.homework.coroutines -import retrofit2.Call import retrofit2.http.GET -interface CatsService { +interface CatFactService { @GET("fact") - fun getCatFact() : Call + suspend fun getCatFact(): FactResponse } \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/CatImageService.kt b/app/src/main/java/otus/homework/coroutines/CatImageService.kt new file mode 100644 index 00000000..3d1b8278 --- /dev/null +++ b/app/src/main/java/otus/homework/coroutines/CatImageService.kt @@ -0,0 +1,9 @@ +package otus.homework.coroutines + +import retrofit2.http.GET + +interface CatImageService { + + @GET("images/search") + suspend fun getCatImage(): List +} \ No newline at end of file diff --git a/app/src/main/java/otus/homework/coroutines/CatsCoroutineContext.kt b/app/src/main/java/otus/homework/coroutines/CatsCoroutineContext.kt new file mode 100644 index 00000000..0a33c07e --- /dev/null +++ b/app/src/main/java/otus/homework/coroutines/CatsCoroutineContext.kt @@ -0,0 +1,19 @@ +package otus.homework.coroutines + +import kotlinx.coroutines.CoroutineExceptionHandler +import kotlinx.coroutines.CoroutineName +import kotlin.coroutines.CoroutineContext + +/** + * Вынесено отдельно, так как используется, как в презентере, так и во ViewModel + */ + +fun getCoroutineContext(): CoroutineContext = getCatsExceptionHandler() + getCatsCoroutineName() + +fun getCatsExceptionHandler() = + CoroutineExceptionHandler { _, e -> + CrashMonitor.trackWarning(e) + } + +fun getCatsCoroutineName() = + CoroutineName("CatsCoroutine") \ 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 e4b05120..9014e5bc 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsPresenter.kt @@ -1,28 +1,65 @@ package otus.homework.coroutines -import retrofit2.Call -import retrofit2.Callback -import retrofit2.Response +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import java.net.SocketTimeoutException + +private const val PRESENTER_CAT_JOB_KEY = "CatJob" class CatsPresenter( - private val catsService: CatsService + private val catFactService: CatFactService, + private val catImageService: CatImageService, + private val scope: CoroutineScope = PresenterScope(), + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, + private val isDataLoadedCallbaсk: (Boolean) -> Unit ) { private var _catsView: ICatsView? = null fun onInitComplete() { - catsService.getCatFact().enqueue(object : Callback { - - override fun onResponse(call: Call, response: Response) { - if (response.isSuccessful && response.body() != null) { - _catsView?.populate(response.body()!!) - } + scope.launch { + val factResponseDeffered = scope.async(ioDispatcher) { + catFactService.getCatFact() } + val imageResponseDeffered = scope.async(ioDispatcher) { + catImageService.getCatImage() + } + + val result = try { + /** Тестовое пробрасывание SocketTimeoutException для проверки */ +// throw SocketTimeoutException() - override fun onFailure(call: Call, t: Throwable) { - CrashMonitor.trackWarning() + val factResponse = factResponseDeffered.await() + val imageResponse = imageResponseDeffered.await() + val imageResponseFirstElement = imageResponse.firstOrNull() + ?: return@launch + + val cat = mapServerResponseToCat( + factResponse = factResponse, + imageResponse = imageResponseFirstElement + ) + + Result.Success(cat) + } catch (e: CancellationException) { + throw e + } catch (e: SocketTimeoutException) { + Result.Error.SocketError + } catch (e: Throwable) { + CrashMonitor.trackWarning(e) + Result.Error.OtherError(e) } - }) + + /** + * Логика показа Тоста находится внутри View, + * работает в зависимости от результата + */ + _catsView?.populate(result) + isDataLoadedCallbaсk(true) + } } fun attachView(catsView: ICatsView) { diff --git a/app/src/main/java/otus/homework/coroutines/CatsView.kt b/app/src/main/java/otus/homework/coroutines/CatsView.kt index be04b2a8..b5388b69 100644 --- a/app/src/main/java/otus/homework/coroutines/CatsView.kt +++ b/app/src/main/java/otus/homework/coroutines/CatsView.kt @@ -2,31 +2,84 @@ package otus.homework.coroutines import android.content.Context import android.util.AttributeSet +import android.util.TypedValue 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 +/** + * Считаю, что методы во вью не нужно делать suspend. + * Если ответ от сервера получен, то нет смысла создавать точку приостановки в данных функциях, + * это лишняя генерация кода под капотом в suspend функциях. + */ class CatsView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr), ICatsView { - var presenter :CatsPresenter? = null + var presenter: CatsPresenter? = null + + var viewModel: CatsViewModel? = null override fun onFinishInflate() { super.onFinishInflate() findViewById