Skip to content

HW2 #214

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: development
Choose a base branch
from
Open

HW2 #214

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
1 change: 1 addition & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,5 @@ 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.2.0"
}
2 changes: 1 addition & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Coroutines">
<activity android:name=".MainActivity"
<activity android:name=".MainActivity2"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Expand Down
6 changes: 6 additions & 0 deletions app/src/main/java/otus/homework/coroutines/ApiResult.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package otus.homework.coroutines

sealed class ApiResult<out T: Any> {
data class Success<out T: Any>(val data: T) : ApiResult<T>()
data class Error(val error: Throwable) : ApiResult<Nothing>()
}
3 changes: 3 additions & 0 deletions app/src/main/java/otus/homework/coroutines/CatapiImage.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package otus.homework.coroutines

class CatapiImage : ArrayList<CatapiImageItem>()
8 changes: 8 additions & 0 deletions app/src/main/java/otus/homework/coroutines/CatapiImageItem.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package otus.homework.coroutines

data class CatapiImageItem(
val height: Int,
val id: String,
val url: String,
val width: Int
)
35 changes: 0 additions & 35 deletions app/src/main/java/otus/homework/coroutines/CatsPresenter.kt

This file was deleted.

7 changes: 5 additions & 2 deletions app/src/main/java/otus/homework/coroutines/CatsService.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package otus.homework.coroutines

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Url

interface CatsService {

@GET("fact")
fun getCatFact() : Call<Fact>
suspend fun getCatFact() : Fact

@GET
suspend fun getImg(@Url url:String = "https://api.thecatapi.com/v1/images/search") : CatapiImage
}
24 changes: 4 additions & 20 deletions app/src/main/java/otus/homework/coroutines/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,14 @@ 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 android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import com.squareup.picasso.Picasso

class CatsView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr), ICatsView {

var presenter :CatsPresenter? = null

override fun onFinishInflate() {
super.onFinishInflate()
findViewById<Button>(R.id.button).setOnClickListener {
presenter?.onInitComplete()
}
}

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

interface ICatsView {

fun populate(fact: Fact)
}
) : ConstraintLayout(context, attrs, defStyleAttr){}
46 changes: 46 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,46 @@
package otus.homework.coroutines

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.launch
import java.net.SocketTimeoutException

class CatsViewModel(
private val catsService: CatsService
) : ViewModel() {

private val _liveData = MutableLiveData<ApiResult<Content>>()
val liveData: LiveData<ApiResult<Content>> = _liveData

val context = CoroutineExceptionHandler { _, throwable ->
CrashMonitor.trackWarning(throwable.message.toString())
} + SupervisorJob()

init {
populate()
}

fun populate() {
viewModelScope.launch(context) {
val resultFact = async { catsService.getCatFact() }
val resultImg = async { catsService.getImg() }
try {
val content = Content(resultImg.await(), resultFact.await())
_liveData.value = ApiResult.Success(content)
} catch (_: CancellationException) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Тут пробросить нужно дальше

} catch (e: SocketTimeoutException) {
_liveData.value =
ApiResult.Error(Throwable("Не удалось получить ответ от сервером"))
} catch (e: Exception) {
_liveData.value = ApiResult.Error(Throwable(e.message))
}
}
}
}
6 changes: 6 additions & 0 deletions app/src/main/java/otus/homework/coroutines/Content.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package otus.homework.coroutines

data class Content(
val catapiImage: CatapiImage,
val fact: Fact,
)
5 changes: 4 additions & 1 deletion app/src/main/java/otus/homework/coroutines/CrashMonitor.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package otus.homework.coroutines

import android.util.Log

object CrashMonitor {

/**
* Pretend this is Crashlytics/AppCenter
*/
fun trackWarning() {
fun trackWarning(msg: String) {
Log.e("CrashMonitor", msg)
}
}
30 changes: 0 additions & 30 deletions app/src/main/java/otus/homework/coroutines/MainActivity.kt

This file was deleted.

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

import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.squareup.picasso.Picasso

class MainActivity2 : AppCompatActivity() {


private val diContainer = DiContainer()
val viewModel by lazy(LazyThreadSafetyMode.NONE) {
ViewModelProvider(this,
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return CatsViewModel(diContainer.service) as T
}
}
)[CatsViewModel::class.java]
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val view = layoutInflater.inflate(R.layout.activity_main, null)
setContentView(view)

findViewById<Button>(R.id.button).setOnClickListener {
viewModel.populate()
}

viewModel.liveData.observe(this) { result ->
when (result){
is ApiResult.Error ->
Toast.makeText(this, result.error.message, Toast.LENGTH_LONG).show()
is ApiResult.Success -> {
Picasso.get().load(result.data.catapiImage[0].url)
.into(findViewById<ImageView>(R.id.fact_imgView))
findViewById<TextView>(R.id.fact_textView).text = result.data.fact.fact
}
}
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package otus.homework.coroutines

class PresentationMopdel {
}
10 changes: 10 additions & 0 deletions app/src/main/java/otus/homework/coroutines/PresenterScope.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package otus.homework.coroutines

import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext

class PresenterScope(override val coroutineContext: CoroutineContext = CoroutineName("CatsCoroutine") + Dispatchers.Main) : CoroutineScope {
}
22 changes: 21 additions & 1 deletion app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,27 @@
android:layout_width="match_parent"
android:padding="16dp"
android:layout_height="match_parent"
tools:context=".MainActivity">
tools:context=".MainActivity2">

<ImageView
android:id="@+id/fact_imgView"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="fitXY"
app:layout_constraintBottom_toTopOf="@+id/fact_textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/fact_imgView"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="fitXY"
app:layout_constraintBottom_toTopOf="@+id/fact_textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/fact_textView"
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<resources>
<string name="app_name">Cat Facts </string>
<string name="more_facts">More Facts</string>
<string name="socket_timeout_exception">Не удалось получить ответ от сервером</string>
</resources>