Skip to content

Instantly share code, notes, and snippets.

View luciofm's full-sized avatar

Lucio Maciel luciofm

View GitHub Profile
@luciofm
luciofm / ChatRoomsFragment.kt
Last active June 13, 2020 14:33
How to run LiveData transformations on a coroutine
class ChatRoomsFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProviders.of(this, factory).get(ChatRoomsViewModel::class.java)
subscribeUi()
}
private fun subscribeUi() {
@luciofm
luciofm / batch.kt
Last active November 26, 2018 18:59
Batch actor with coroutines
private inline fun <T> createBatchActor(context: CoroutineContext = CommonPool,
parent: Job? = null,
maxSize: Int = 100,
maxTime: Int = 500,
crossinline block: (List<T>) -> Unit): SendChannel<T> {
return actor(context, parent = parent) {
val batch = ArrayList<T>(maxSize)
var deadline = 0L // deadline for sending this batch to callback block
while(true) {
@luciofm
luciofm / DebounceLiveData.kt
Created May 13, 2019 16:11
A Debouncing LiveData helper
class DebounceLiveData<Source>(
private val source: LiveData<Source>,
private val debounceMs: Long
) : LiveData<Source>(), CoroutineScope {
private val job = SupervisorJob()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
private var debounceJob: Job? = null
private val observer = Observer<Source> { source ->