-
Notifications
You must be signed in to change notification settings - Fork 239
Coroutines Homework by Diana #253
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
Changes from 3 commits
1582da9
90aa0b8
509ca98
b9b2e5f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package otus.homework.coroutines | ||
|
||
import retrofit2.Response | ||
import retrofit2.http.GET | ||
|
||
interface CatsImageService { | ||
|
||
@GET("v1/images/search") | ||
suspend fun getCatImage(): Response<List<Image>> | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,28 +1,50 @@ | ||
package otus.homework.coroutines | ||
|
||
import retrofit2.Call | ||
import retrofit2.Callback | ||
import retrofit2.Response | ||
import android.content.Context | ||
import kotlinx.coroutines.async | ||
import kotlinx.coroutines.cancelChildren | ||
import kotlinx.coroutines.launch | ||
import kotlinx.coroutines.supervisorScope | ||
import java.net.SocketTimeoutException | ||
|
||
class CatsPresenter( | ||
private val catsService: CatsService | ||
private val catsService: CatsService, | ||
private val catsImageService: CatsImageService, | ||
val context: Context | ||
) { | ||
|
||
private var _catsView: ICatsView? = null | ||
private val presenterScope = PresenterScope() | ||
|
||
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.coroutineContext.cancelChildren() | ||
presenterScope.launch { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Вот здесь создается дочерняя джоба. Ее и надо трекать. |
||
try { | ||
supervisorScope { | ||
val factDeferred = async { catsService.getCatFact() } | ||
val imageDeferred = async { catsImageService.getCatImage() } | ||
val factResponse = factDeferred.await() | ||
val imageResponse = imageDeferred.await() | ||
|
||
if (factResponse.isSuccessful && factResponse.body() != null | ||
&& imageResponse.isSuccessful && imageResponse.body() != null | ||
) { | ||
_catsView?.populate( | ||
PresentationFact( | ||
factResponse.body()?.fact, | ||
imageResponse.body()?.get(0)?.imageUrl | ||
) | ||
) | ||
} | ||
} | ||
} catch (e: Exception) { | ||
if (e is SocketTimeoutException) { | ||
_catsView?.showToast(context.getString(R.string.server_error)) | ||
} else { | ||
_catsView?.showToast(e.message ?: context.getString(R.string.error)) | ||
CrashMonitor.trackWarning() | ||
} | ||
} | ||
|
||
override fun onFailure(call: Call<Fact>, t: Throwable) { | ||
CrashMonitor.trackWarning() | ||
} | ||
}) | ||
} | ||
} | ||
|
||
fun attachView(catsView: ICatsView) { | ||
|
@@ -32,4 +54,8 @@ class CatsPresenter( | |
fun detachView() { | ||
_catsView = null | ||
} | ||
|
||
fun cancel() { | ||
presenterScope.cancel() | ||
} | ||
} |
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("fact") | ||
fun getCatFact() : Call<Fact> | ||
suspend fun getCatFact(): Response<Fact> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можно не писать Response. А просто |
||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package otus.homework.coroutines | ||
|
||
import androidx.lifecycle.ViewModel | ||
import androidx.lifecycle.viewModelScope | ||
import kotlinx.coroutines.CoroutineExceptionHandler | ||
import kotlinx.coroutines.async | ||
import kotlinx.coroutines.flow.MutableStateFlow | ||
import kotlinx.coroutines.flow.StateFlow | ||
import kotlinx.coroutines.launch | ||
|
||
class CatsViewModel( | ||
private val catsService: CatsService, | ||
private val catsImageService: CatsImageService | ||
) : ViewModel() { | ||
val handler = CoroutineExceptionHandler { _, exception -> | ||
_factState.value = Result.Error(exception) | ||
CrashMonitor.trackWarning() | ||
} | ||
private val _factState = MutableStateFlow<Result>(Result.Loading) | ||
val factState: StateFlow<Result> = _factState | ||
|
||
fun onInitComplete() { | ||
_factState.value = Result.Loading | ||
viewModelScope.launch(handler) { | ||
val factDeferred = async { catsService.getCatFact() } | ||
val imageDeferred = async { catsImageService.getCatImage() } | ||
val factResponse = factDeferred.await() | ||
val imageResponse = imageDeferred.await() | ||
|
||
if (factResponse.isSuccessful && factResponse.body() != null | ||
&& imageResponse.isSuccessful && imageResponse.body() != null | ||
) { | ||
_factState.value = Result.Success( | ||
PresentationFact( | ||
factResponse.body()?.fact, | ||
imageResponse.body()?.get(0)?.imageUrl | ||
) | ||
) | ||
} | ||
} | ||
} | ||
} | ||
|
||
sealed class Result() { | ||
data class Success(val data: PresentationFact) : Result() | ||
data class Error(val exception: Throwable) : Result() | ||
object Loading : Result() | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package otus.homework.coroutines | ||
|
||
import androidx.lifecycle.ViewModel | ||
import androidx.lifecycle.ViewModelProvider | ||
|
||
class CatsViewModelFactory( | ||
private val catsService: CatsService, | ||
private val catImagesService: CatsImageService | ||
) : ViewModelProvider.Factory { | ||
override fun <T : ViewModel> create(modelClass: Class<T>): T { | ||
if (modelClass.isAssignableFrom(CatsViewModel::class.java)) { | ||
return CatsViewModel(catsService, catImagesService) as T | ||
} | ||
throw IllegalArgumentException("Unknown ViewModel class") | ||
} | ||
} |
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 Image( | ||
@field:SerializedName("url") | ||
val imageUrl: String? | ||
) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,60 @@ | ||
package otus.homework.coroutines | ||
|
||
import androidx.appcompat.app.AppCompatActivity | ||
import android.os.Bundle | ||
import androidx.activity.viewModels | ||
import androidx.appcompat.app.AppCompatActivity | ||
import androidx.lifecycle.lifecycleScope | ||
import kotlinx.coroutines.launch | ||
import java.net.SocketTimeoutException | ||
|
||
class MainActivity : AppCompatActivity() { | ||
|
||
lateinit var catsPresenter: CatsPresenter | ||
// lateinit var catsPresenter: CatsPresenter | ||
|
||
private val diContainer = DiContainer() | ||
|
||
private val viewModel: CatsViewModel by viewModels { | ||
CatsViewModelFactory( | ||
catsService = diContainer.catsService, | ||
catImagesService = diContainer.catsImageservice | ||
) | ||
} | ||
|
||
override fun onCreate(savedInstanceState: Bundle?) { | ||
super.onCreate(savedInstanceState) | ||
|
||
val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView | ||
setContentView(view) | ||
|
||
catsPresenter = CatsPresenter(diContainer.service) | ||
view.presenter = catsPresenter | ||
catsPresenter.attachView(view) | ||
catsPresenter.onInitComplete() | ||
} | ||
|
||
override fun onStop() { | ||
if (isFinishing) { | ||
catsPresenter.detachView() | ||
// catsPresenter = CatsPresenter(diContainer.catsService, diContainer.catsImageservice, this) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Закоментированный код лучше удалять, если он не несет какойго то вопроса. |
||
view.viewModel = viewModel | ||
// catsPresenter.attachView(view) | ||
viewModel.onInitComplete() | ||
|
||
lifecycleScope.launch { | ||
viewModel.factState.collect { result -> | ||
when (result) { | ||
is Result.Success -> view.populate(result.data) | ||
|
||
is Result.Error -> { | ||
if (result.exception is SocketTimeoutException) { | ||
view.showToast(getString(R.string.server_error)) | ||
} else { | ||
view.showToast(result.exception.message ?: getString(R.string.error)) | ||
} | ||
} | ||
|
||
is Result.Loading -> {} | ||
} | ||
} | ||
} | ||
super.onStop() | ||
} | ||
|
||
// override fun onStop() { | ||
// if (isFinishing) { | ||
// catsPresenter.detachView() | ||
// catsPresenter.cancel() | ||
// } | ||
// super.onStop() | ||
// } | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
package otus.homework.coroutines | ||
|
||
data class PresentationFact( | ||
val fact: String?, | ||
val imageUrl: String? | ||
) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
package otus.homework.coroutines | ||
|
||
import kotlinx.coroutines.CoroutineName | ||
import kotlinx.coroutines.CoroutineScope | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.SupervisorJob | ||
import kotlin.coroutines.CoroutineContext | ||
|
||
class PresenterScope() : CoroutineScope { | ||
private val job = SupervisorJob() | ||
|
||
override val coroutineContext: CoroutineContext | ||
get() = Dispatchers.Main + job + CoroutineName("CatsCoroutine") | ||
|
||
fun cancel() { | ||
job.cancel() | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Думаю, что не самое удачное решение. И здесь как минимум вы путаете с ним. Также, если вы вызываете
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. В общем. CoroutineScope лучше отменять через уже существующий метод CoroutineScope.cancel. А отменять джобы - это отменять джобы. Там где сделали launch, там и трекайте. |
||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,7 @@ | ||
<resources> | ||
<string name="app_name">Cat Facts </string> | ||
<string name="more_facts">More Facts</string> | ||
<string name="server_error">Не удалось получить ответ от сервера</string> | ||
<string name="error">Что-то пошло не так</string> | ||
<string name="cat_image">Фото кота</string> | ||
</resources> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут тоже можно не писать Response.