Skip to content

Instantly share code, notes, and snippets.

@RubyLichtenstein
RubyLichtenstein / PainlessFragmentArguments.md
Last active February 11, 2021 00:40
Painless android fragments with Kotlin

Starting new fragments with Kotlin is easy

Example

val user = User(id = "id", name = "Ruby")
val userFragment: UserFragment = newFragment<User, UserFragment>(user)

How this magic works

class LifeCycle {
open class BaseActivity : Activity(), CoroutineScope {
private val job = SupervisorJob()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun onDestroy() {
super.onDestroy()
job.cancel()
//run array of (suspend () -> Unit) in parallel
suspend fun parallel(vararg blocks: suspend () -> Unit) = runBlocking {
for (block in blocks) {
withContext(Dispatchers.Default) { block() }
}
}
//run 2 functinos in pararllel then marge the result into pair
suspend fun <T1, T2> parallel2(block1: suspend () -> T1, block2: suspend () -> T2): Pair<T1, T2> =
runBlocking {
package com.tandoo.android.libs.repo
import android.content.Context
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.DocumentChange
import com.tandoo.android.featuers.user.Cacheable
import com.tandoo.android.firebase.firestoreInstance
import com.tandoo.android.libs.mapParallel
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.tasks.await
suspend fun parallel(vararg blocks: suspend () -> Unit) {
for (block in blocks) {
GlobalScope.async { block() }.await()
}
}
suspend fun <T1, T2> parallel2(block1: suspend () -> T1, block2: suspend () -> T2): Pair<T1, T2> {
return Pair(GlobalScope.async { block1() }.await(), GlobalScope.async { block2() }.await())
}
inline fun <reified T> DatabaseReference.toLiveData(): LiveData<T> {
val liveData: MutableLiveData<T> = MutableLiveData()
addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
dataSnapshot.children.forEach {
liveData.value = it.getValue<T>(T::class.java)
}
}
override fun onCancelled(databaseError: DatabaseError) {
@RubyLichtenstein
RubyLichtenstein / RxRv.kt
Last active May 13, 2018 07:41
RxRecyclerView.kt
abstract class RxRvAdapter<T : RxRvItem<*>, VH : RecyclerView.ViewHolder>(val events: Observable<T>) :
RecyclerView.Adapter<VH>() {
lateinit var sortedList: SortedList<T>
lateinit var obs: Observable<T>
private val itemCountObservable = BehaviorSubject.createDefault(0)
abstract fun createSortedList(): SortedList<T>
@RubyLichtenstein
RubyLichtenstein / MigrationToRxJava2.x.MD
Last active July 30, 2020 00:18
Migration To RxJava 2.x

Migration To RxJava 2.x

Introduction

In this post, I will show some points to be aware of in RxJava v1.x to v2.x migration.

The post divided to 3 sections

  • The Good
    • Naming
    • Coexistence
  • Interoperability