LoginSignup
51
42

More than 5 years have passed since last update.

よりRxらしくRecyclerViewの一番下までスクロールした時にロードする実装

Last updated at Posted at 2017-07-13

同じことをやっている記事はすでに沢山あるのですが、よりRxらしく書ける方法を考えてみました。
使用している言語はKotlinです。

参考にさせていただいた記事:
http://qiita.com/konifar/items/e57c47bfb93d0d40ef59
http://sys1yagi.hatenablog.com/entry/2016/02/23/185543

使うもの

  • rxjava2
  • rxkotlin
  • rxbinding-recyclerview-v7
  • rxbinding-recyclerview-v7-kotlin

実装

まず、シンプルな実装

val layoutManager = LinearLayoutManager(...)

recyclerView
        .scrollEvents()
        .filter { layoutManager.itemCount - 1 <= layoutManager.findLastVisibleItemPosition() }
        .subscribe { loadMore() }

これだけです。rxbinding-recyclerview-v7先生のおかげでだいぶスッキリ書けました。

さらに、読み込み完了まで追加ロードを止めたい場合は
読み込み完了を通知するSubjectを用意しておいて、

val loadCompletedStream = PublishSubject.create<Unit>()
recyclerView
        .scrollEvents()
        .skipUntil(loadCompletedStream)
        .filter { layoutManager.itemCount - 1 <= layoutManager.findLastVisibleItemPosition() }
        .take(1)
        .repeat()
        .subscribe { loadMore() }

こうしてskipUntil/take/repeatをかませてあげます。
あとはロード完了時にloadCompletedStream.onNext(Unit)を呼んであげるだけでイベントが再度流れるようになります。

以上です。

51
42
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
51
42