Skip to content

Instantly share code, notes, and snippets.

@RubyLichtenstein
Last active May 13, 2018 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RubyLichtenstein/b97bc877d26e0aaa0961b3b2f4295d0b to your computer and use it in GitHub Desktop.
Save RubyLichtenstein/b97bc877d26e0aaa0961b3b2f4295d0b to your computer and use it in GitHub Desktop.
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>
//must call
protected fun init() {
this.sortedList = createSortedList()
this.obs = bindEventsToSortedList(events, sortedList)
this.obs.subscribe({}, Timber::e)
}
fun itemCountObservable() = itemCountObservable as Observable<Int>
private fun bindEventsToSortedList(
events: Observable<T>,
sortedList: SortedList<T>
)
: Observable<T> {
return events.doOnNext({
when (it.action) {
Action.ADD -> sortedList.add(it)
Action.REMOVE -> {
sortedList.remove(it)
}
}
afterEvent()
})
}
override fun getItemCount() = sortedList.size()
private fun afterEvent() {
itemCountObservable.onNext(itemCount)
}
}
abstract class RxRvItem<T>(
open val action: Action,
open val value: T
) {
abstract fun compareTo(other: RxRvItem<T>): Int
abstract fun areContentsTheSame(other: RxRvItem<T>): Boolean
abstract fun areItemsTheSame(other: RxRvItem<T>): Boolean
}
enum class Action {
ADD,
REMOVE
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment