Last active
January 6, 2020 10:47
-
-
Save jinqian/125c159fc06eac8ed9868b973f846228 to your computer and use it in GitHub Desktop.
PokedexViewModel.kt
This file contains 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
import androidx.lifecycle.LiveData | |
import androidx.lifecycle.MutableLiveData | |
import androidx.lifecycle.ViewModel | |
import androidx.lifecycle.viewModelScope | |
import io.grpc.okhttp.OkHttpChannelBuilder | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.launch | |
class PokedexViewModel : ViewModel() { | |
val pokemonLiveDate: LiveData<GetPokemonResult> get() = _pokemonLiveData | |
private val _pokemonLiveData = MutableLiveData<GetPokemonResult>() | |
fun getPokemon(host: String, portStr: String, message: String) { | |
viewModelScope.launch(Dispatchers.IO) { | |
try { | |
val port = if (portStr.isEmpty()) 0 else portStr.toInt() | |
val channel = OkHttpChannelBuilder.forAddress(host, port).usePlaintext().build() | |
val stub = PokedexGrpc.newBlockingStub(channel) | |
val request = PokedexRequest.newBuilder().setEnglishName(message.trim()).build() | |
val reply = stub.getPokemon(request) | |
_pokemonLiveData.postValue(GetPokemonResult.Success(reply)) | |
channel.shutdown() | |
} catch (e: Exception) { | |
e.printStackTrace() | |
_pokemonLiveData.postValue(GetPokemonResult.Error(e)) | |
} | |
} | |
} | |
} | |
sealed class GetPokemonResult { | |
data class Success(val reply: PokedexReply) : GetPokemonResult() | |
data class Error(val exception: Exception) : GetPokemonResult() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment