Last active
May 13, 2018 07:41
-
-
Save RubyLichtenstein/b97bc877d26e0aaa0961b3b2f4295d0b to your computer and use it in GitHub Desktop.
RxRecyclerView.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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