-
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
Closed
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
1582da9
Задание 1 (переход с коллбеков на suspend и корутины)
diana-cyber-w 90aa0b8
Задание 2 (добавление запроса с картинками)
diana-cyber-w 509ca98
Задание 3 (добавлена ViewModel)
diana-cyber-w b9b2e5f
Переделан presenterscope и удален response из сетевых запросов
diana-cyber-w File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
9 changes: 9 additions & 0 deletions
9
app/src/main/java/otus/homework/coroutines/CatsImageService.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
package otus.homework.coroutines | ||
|
||
import retrofit2.http.GET | ||
|
||
interface CatsImageService { | ||
|
||
@GET("v1/images/search") | ||
suspend fun getCatImage(): List<Image> | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,28 +1,48 @@ | ||
package otus.homework.coroutines | ||
|
||
import retrofit2.Call | ||
import retrofit2.Callback | ||
import retrofit2.Response | ||
import android.content.Context | ||
import kotlinx.coroutines.CoroutineName | ||
import kotlinx.coroutines.CoroutineScope | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.Job | ||
import kotlinx.coroutines.async | ||
import kotlinx.coroutines.cancel | ||
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 = | ||
CoroutineScope(Dispatchers.Main + Job() + 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.coroutineContext[Job]?.cancel() | ||
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() | ||
|
||
_catsView?.populate( | ||
PresentationFact(factResponse.fact, imageResponse.first().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 +52,8 @@ class CatsPresenter( | |
fun detachView() { | ||
_catsView = null | ||
} | ||
|
||
fun cancel() { | ||
presenterScope.cancel() | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,9 @@ | ||
package otus.homework.coroutines | ||
|
||
import retrofit2.Call | ||
import retrofit2.http.GET | ||
|
||
interface CatsService { | ||
|
||
@GET("fact") | ||
fun getCatFact() : Call<Fact> | ||
suspend fun getCatFact(): Fact | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
41 changes: 41 additions & 0 deletions
41
app/src/main/java/otus/homework/coroutines/CatsViewModel.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
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() | ||
|
||
_factState.value = Result.Success( | ||
PresentationFact(factResponse.fact, imageResponse.first().imageUrl) | ||
) | ||
} | ||
} | ||
} | ||
|
||
sealed class Result() { | ||
data class Success(val data: PresentationFact) : Result() | ||
data class Error(val exception: Throwable) : Result() | ||
object Loading : Result() | ||
} |
16 changes: 16 additions & 0 deletions
16
app/src/main/java/otus/homework/coroutines/CatsViewModelFactory.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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? | ||
) |
44 changes: 31 additions & 13 deletions
44
app/src/main/java/otus/homework/coroutines/MainActivity.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,48 @@ | ||
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 | ||
|
||
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() | ||
view.viewModel = viewModel | ||
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() | ||
} | ||
} |
6 changes: 6 additions & 0 deletions
6
app/src/main/java/otus/homework/coroutines/PresentationFact.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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? | ||
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Так отменять неправильно. Так мы отменяем родительскую джобу. А надо дочернюю.
Правильно было бы написать что-то типа такого:
private var loadJob: Job? = null