Skip to content

Instantly share code, notes, and snippets.

View wellingtoncosta's full-sized avatar

Wellington Pereira wellingtoncosta

  • Fortaleza, Brazil
  • 20:23 (UTC -03:00)
View GitHub Profile
#!/bin/sh
set -eu
# Docker
sudo apt remove --yes docker docker-engine docker.io \
&& sudo apt update \
&& sudo apt --yes --no-install-recommends install \
apt-transport-https \
ca-certificates \
fun main() {
GlobalScope.launch {
// do some heavy work
}
}
class ListUsersViewModel(
private val repository: UserRepository
) : CoroutineViewModel() {
private val users: MutableLiveData<List<User>> = MutableLiveData()
private val loading: MutableLiveData<Boolean> = MutableLiveData()
private val error: MutableLiveData<Throwable> = MutableLiveData()
fun users() = users as LiveData<List<User>>
fun loading() = loading as LiveData<Boolean>
open class CoroutineViewModel : ViewModel(), CoroutineScope {
override val coroutineContext = Main
protected val jobs = ArrayList<Job>()
infix fun ArrayList<Job>.add(job: Job) { this.add(job) }
override fun onCleared() {
super.onCleared()
class UserDataRepository(
private val api: GithubApi
) : UserRepository {
override suspend fun getAll() = withContext(IO) {
async { api.getAll().await().map { it.toModel() } }
}
override suspend fun getByUsername(username: String) = withContext(IO) {
async { api.getByUsername(username).await().toModel() }
interface UserRepository {
suspend fun getAll(): Deferred<List<User>>
suspend fun getByUsername(username: String): Deferred<User>
}
interface GithubApi {
@GET("users")
fun getAll(): Deferred<List<UserResponse>>
@GET("users/{username}")
fun getByUsername(@Path("username") username: String): Deferred<UserResponse>
}
suspend fun loadUserData(username: String): User {
return coroutineScope {
val user = async { loadUser(username) }
val repos = async { loadRepos(username) }
buildUserData(user.await(), repos.await())
}
}
fun main() {
GlobalScope.launch(context = Dispatchers.Main) {
val orders = withContext(context = Dispatchers.IO) {
fetchOrders().await()
}
printOrders(orders)
}
}
fun main() {
GlobalScope.launch {
val orders = fetchOrders().await()
println(orders)
}
}
suspend fun fetchOrders() = GlobalScope.async {
delay(2000) // simulates a external data fetch
listOf(