Skip to content

Instantly share code, notes, and snippets.

View CostaFot's full-sized avatar
🍦

Costa Fotiadis CostaFot

🍦
View GitHub Profile
@CostaFot
CostaFot / .gitignore
Created April 14, 2019 13:45
Android .gitignore template
# Built application files
*.apk
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
@CostaFot
CostaFot / dependencies.gradle
Created June 20, 2019 22:07
Android common dependencies collection
allprojects {
ext {
// NEVER name this block 'android'. Never name *ANY* block android
androidVersions = [
// updated 17/3/2019
androidXVersion : "1.0.0",
livedata : '2.0.0-rc01',
minSdkVersion : 21,
targetSdkVersion : 28,
compileSdkVersion: 28,
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
class PostViewModel(private val redditRepository: RedditRepository) : ViewModel() {
val stateData = MutableLiveData<State>()
fun getRedditPost() {
viewModelScope.launch {
stateData.value = State.Loading
val post: State.Post = redditRepository.getPost()
stateData.value = post
}
class RedditRepository(private val dispatcherProvider: DispatcherProvider) {
suspend fun getPost(): State.Post {
return withContext(dispatcherProvider.io) {
delay(5000)
State.Post("to be fair")
}
}
}
class RedditRepository(private val dispatcherProvider: DispatcherProvider) {
suspend fun getPost(): State.Post {
return withContext(dispatcherProvider.io) {
delay(2000)
State.Post("🐢 SLOW AND STEADY 🐢 WINS THE RACE 🐢 MODS CAN'T BAN ME 🐢 AT THIS PACE 🐢")
}
}
}
interface DispatcherProvider {
val io: CoroutineDispatcher
val ui: CoroutineDispatcher
val default: CoroutineDispatcher
val unconfined: CoroutineDispatcher
}
class DefaultDispatcherProvider(
override val ui: CoroutineDispatcher = Dispatchers.Main,
override val default: CoroutineDispatcher = Dispatchers.Default,
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModelpost.stateData.observe(viewLifecycleOwner, Observer { state ->
when (state) {
State.Loading -> button.text = "Loading"
is State.Post -> button.text = state.text
}
})
fun getRedditPost() {
viewModelScope.launch(Dispatchers.Main) {
stateData.value = State.Loading
val post: State.Post = redditRepository.getPost()
stateData.value = post
}
}