Skip to content

Instantly share code, notes, and snippets.

Wellington Costa WellingtonCosta

View GitHub Profile
View launch_coroutine.kt
fun main() {
GlobalScope.launch {
// do some heavy work
}
}
View users_viewmodel.kt
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>
View base_coroutine_viewmodel.kt
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()
View user_data_repository.kt
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() }
View user_repository_interface.kt
interface UserRepository {
suspend fun getAll(): Deferred<List<User>>
suspend fun getByUsername(username: String): Deferred<User>
}
View github_api.kt
interface GithubApi {
@GET("users")
fun getAll(): Deferred<List<UserResponse>>
@GET("users/{username}")
fun getByUsername(@Path("username") username: String): Deferred<UserResponse>
}
View coroutine_scope_coroutines.kt
suspend fun loadUserData(username: String): User {
return coroutineScope {
val user = async { loadUser(username) }
val repos = async { loadRepos(username) }
buildUserData(user.await(), repos.await())
}
}
View with_context_coroutine.kt
fun main() {
GlobalScope.launch(context = Dispatchers.Main) {
val orders = withContext(context = Dispatchers.IO) {
fetchOrders().await()
}
printOrders(orders)
}
}
View coroutine_async_example.kt
fun main() {
GlobalScope.launch {
val orders = fetchOrders().await()
println(orders)
}
}
suspend fun fetchOrders() = GlobalScope.async {
delay(2000) // simulates a external data fetch
listOf(
View suspend_function.kt
suspend fun doSomeHeavyOperation() {
// do some non blocking operation
}
You can’t perform that action at this time.