Skip to content

homework_2: done #1

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

Closed
Closed
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
9 changes: 9 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,13 @@ dependencies {
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.squareup.picasso:picasso:2.71828'

//coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1'

//SwipeRefreshLayout
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"

//ViewModelScope
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package otus.homework.coroutines

import com.google.gson.annotations.SerializedName

data class CatImageResponse(
@field:SerializedName("file")
val fileName: String = ""
)
54 changes: 42 additions & 12 deletions app/src/main/java/otus/homework/coroutines/CatsPresenter.kt
Original file line number Diff line number Diff line change
@@ -1,35 +1,65 @@
package otus.homework.coroutines

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import android.util.Log
import kotlinx.coroutines.*
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 presenterScope = 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()!!)
presenterScope.launch {
try {
_catsView?.onLoading(true)
val result = withContext(Dispatchers.IO) {
catsService.getCatFact()
}
if (result.isSuccessful) {
_catsView?.populate(Fact(result.body()!!.text))
} else throw Exception("Not successful result")
} catch (ex: Exception) {
when (ex) {
is SocketTimeoutException -> _catsView?.showErrorDialog(ex.localizedMessage ?: "error")
else -> CrashMonitor.trackWarning()
}
} finally {
_catsView?.onLoading(false)
}
}
}

override fun onFailure(call: Call<Fact>, t: Throwable) {
CrashMonitor.trackWarning()
fun loadFactAndImage() {
presenterScope.launch {
try {
val factResult = async(Dispatchers.IO) { catsService.getCatFact() }
val imageResult = async(Dispatchers.IO) { imageService.getCatImage() }
_catsView?.onLoading(true)
if (factResult.await().isSuccessful && imageResult.await().isSuccessful) {
_catsView?.populate(Fact(factResult.await().body()!!.text, imageResult.await().body()!!.fileName))
} else throw Exception("Not successful result")
} catch (ex: Exception) {
when (ex) {
is SocketTimeoutException -> _catsView?.showErrorDialog(ex.localizedMessage ?: "error")
else -> CrashMonitor.trackWarning()
}
} finally {
_catsView?.stopRefreshing()
_catsView?.onLoading(false)
}
})
}
}

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

fun detachView() {
presenterScope.cancel()
_catsView = null
}
}
4 changes: 2 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,10 @@
package otus.homework.coroutines

import retrofit2.Call
import retrofit2.Response
import retrofit2.http.GET

interface CatsService {

@GET("random?animal_type=cat")
fun getCatFact() : Call<Fact>
suspend fun getCatFact(): Response<FactResponse>
}
41 changes: 35 additions & 6 deletions app/src/main/java/otus/homework/coroutines/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,60 @@ package otus.homework.coroutines

import android.content.Context
import android.util.AttributeSet
import android.widget.Button
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import android.widget.*
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.squareup.picasso.Picasso

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

var presenter :CatsPresenter? = null
var presenter: CatsPresenter? = null
private var swipeRefresh: SwipeRefreshLayout? = null
private var factButton: Button? = null

override fun onFinishInflate() {
super.onFinishInflate()
findViewById<Button>(R.id.button).setOnClickListener {
factButton = findViewById<Button>(R.id.button)
factButton?.setOnClickListener {
presenter?.onInitComplete()
}
swipeRefresh = findViewById(R.id.refresh_layout)
swipeRefresh?.setOnRefreshListener {
swipeRefresh?.isRefreshing = true
presenter?.loadFactAndImage()
}
}

override fun populate(fact: Fact) {
findViewById<TextView>(R.id.fact_textView).text = fact.text
if (fact.image.isNotEmpty()) {
Picasso.get().load(fact.image).into(
findViewById<ImageView>(R.id.cat_image_view)
)
}
}

override fun showErrorDialog(message: String) {
Toast.makeText(this.context, message, Toast.LENGTH_LONG).show()
}

override fun stopRefreshing() {
swipeRefresh?.isRefreshing = false
}

override fun onLoading(value: Boolean) {
factButton?.isEnabled = !value
swipeRefresh?.isEnabled = !value
}
}

interface ICatsView {

fun populate(fact: Fact)
fun showErrorDialog(message: String)
fun stopRefreshing()
fun onLoading(value: Boolean)
}
7 changes: 7 additions & 0 deletions app/src/main/java/otus/homework/coroutines/DiContainer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ class DiContainer {
.addConverterFactory(GsonConverterFactory.create())
.build()
}
private val imageRetrofit by lazy {
Retrofit.Builder()
.baseUrl("https://aws.random.cat/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}

val service by lazy { retrofit.create(CatsService::class.java) }
val imageService by lazy { imageRetrofit.create(ImageService::class.java) }
}
22 changes: 2 additions & 20 deletions app/src/main/java/otus/homework/coroutines/Fact.kt
Original file line number Diff line number Diff line change
@@ -1,24 +1,6 @@
package otus.homework.coroutines

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
val text: String = "",
val image: String = ""
)
25 changes: 25 additions & 0 deletions app/src/main/java/otus/homework/coroutines/FactResponse.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package otus.homework.coroutines

import com.google.gson.annotations.SerializedName

data class FactResponse(
@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,
val image: String = ""
)
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.Response
import retrofit2.http.GET

interface ImageService {
@GET("meow")
suspend fun getCatImage(): Response<CatImageResponse>
}
2 changes: 1 addition & 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,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, diContainer.imageService)
view.presenter = catsPresenter
catsPresenter.attachView(view)
catsPresenter.onInitComplete()
Expand Down
64 changes: 64 additions & 0 deletions app/src/main/java/otus/homework/coroutines/MainViewModel.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package otus.homework.coroutines

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.*
import java.net.SocketTimeoutException

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

private val _resultLiveData = MutableLiveData<Result>()
val resultLiveData: LiveData<Result>
get() = _resultLiveData
private val handler = CoroutineExceptionHandler { _, exception ->
CrashMonitor.trackWarning()
_resultLiveData.postValue(Result.Error(exception.localizedMessage ?: "error"))
}

init {
onInitComplete()
}

fun onInitComplete() {
viewModelScope.launch(handler) {
_resultLiveData.postValue(Result.Loading)
try {
val result = withContext(Dispatchers.IO) {
catsService.getCatFact()
}
if (result.isSuccessful) {
_resultLiveData.postValue(Result.Success(Fact(result.body()!!.text)))
} else throw Exception("Not successful result")
} catch (ex: SocketTimeoutException) {
_resultLiveData.postValue(Result.Error(ex.localizedMessage ?: "error"))
}
}
}

fun loadFactAndImage() {
viewModelScope.launch(handler) {
val factResult = async(Dispatchers.IO) { catsService.getCatFact() }
val imageResult = async(Dispatchers.IO) { imageService.getCatImage() }
_resultLiveData.postValue(Result.Loading)
try {
if (factResult.await().isSuccessful && imageResult.await().isSuccessful) {
_resultLiveData.postValue(Result.Success(Fact(factResult.await().body()!!.text, imageResult.await().body()!!.fileName)))
} else throw Exception("Not successful result")
} catch (ex: SocketTimeoutException) {
_resultLiveData.postValue(Result.Error(ex.localizedMessage ?: "error"))
}
}
}

sealed class Result {
data class Success(val data: Fact) : Result()
data class Error(val message: String) : Result()
object Loading : Result()
}

}
Loading