Skip to content

Instantly share code, notes, and snippets.

View alfonsogarsan's full-sized avatar

Alfonso García Santiago alfonsogarsan

View GitHub Profile
fun AnswerApiDto.toDomain() = Answer(
answer = answer,
forced = forced,
imageUrl = image
)
class AnswerRepositoryImpl(
private val answerApiService: AnswerApiService
//In this example there isn't DAO for answer
) : AnswerRepository{
override fun getAnswer(): Observable<Answer> {
return answerApiService.getAnswer().map { it.toDomain()}
}
}
.......
activity?.let {
//we pass the activity as lifecycle owner
answerViewModel.answer.observe(it, Observer { result ->
when (result) {
is Result.Success -> {
loadGifFromURL(result.value.image, requireContext(), answerGif)
}
is Result.Failure -> {
sealed class Result<T> {
data class Success<T>(val value: T) : Result<T>()
data class Failure<T>(val throwable: Throwable) : Result<T>()
}
class AnswerViewModel (
private val answerRepository: AnswerRepository
): ViewModel() {
private var disposable: Disposable? = null
val answer by lazy {
MutableLiveData<Result<Answer>>()
}
object RetrofitClient {
private val retrofit by lazy {
val okHttpClient = OkHttpClient.Builder()
.build()
Retrofit.Builder()
.baseUrl("https://yesno.wtf/")
.client(okHttpClient)
interface AnswerApiService {
@GET("/api")
fun getAnswer(): Observable<AnswerApiDto>
}
data class AnswerApiDto (
@SerializedName("answer")
val answer: String,
@SerializedName("forced")
val forced: Boolean,
@SerializedName("image")
val image: String
)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.alfgarsan.android.retrofitrxyesno"
@alfonsogarsan
alfonsogarsan / kotlin-coroutines-example-01.kt
Last active July 21, 2020 08:54
This is a little example of how to compose two coroutines (IO) to work concurrently and to make parent coroutine to suspend in await calls
import kotlinx.coroutines.*
fun main() {
GlobalScope.launch {
println("[${Thread.currentThread().name}] Before asyncs")
val one = async (Dispatchers.IO) { doSomething1() }
val two = async (Dispatchers.IO) { doSomething2() }
println("[${Thread.currentThread().name}] After asyncs")
println("[${Thread.currentThread().name}] The answer is ${one.await() + two.await()}")