Skip to content
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

Add corutines to consume pokemons service #181

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
4 changes: 0 additions & 4 deletions .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/kotlinc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package dev.marcosfarias.pokedex.repository

import dev.marcosfarias.pokedex.model.Pokemon
import retrofit2.Call
import retrofit2.http.GET

interface PokemonService {
@GET("pokemon.json")
fun get(): Call<List<Pokemon>>
fun get(): List<Pokemon>
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package dev.marcosfarias.pokedex.ui.pokedex

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dev.marcosfarias.pokedex.database.dao.PokemonDAO
import dev.marcosfarias.pokedex.model.Pokemon
import dev.marcosfarias.pokedex.repository.PokemonService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
Expand All @@ -19,24 +22,14 @@ class PokedexViewModel(
}

private fun initNetworkRequest() {
val call = pokemonService.get()

call.enqueue(object : Callback<List<Pokemon>?> {
override fun onResponse(
call: Call<List<Pokemon>?>?,
response: Response<List<Pokemon>?>?
) {
response?.body()?.let { pokemons: List<Pokemon> ->
thread {
pokemonDAO.add(pokemons)
}
}
}

override fun onFailure(call: Call<List<Pokemon>?>?, t: Throwable?) {
// TODO handle failure
viewModelScope.launch(Dispatchers.IO) {
try {
val response = pokemonService.get()
pokemonDAO.add(response)
} catch (e: Exception) {
e.printStackTrace()
}
})
}
}

fun getListPokemon() = pokemonDAO.all()
Expand Down