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
| 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> |
| 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) { |
| 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()) | |
| } |
| 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 |
| //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 { |
| 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() |