【Android】initLoaderとrestartLoader

AsyncLoaderを使っていると謎の挙動に出くわしたため調査

事象

 ①initLoader()→forceLoad()を実施

 ②onLoadFinished()が呼び出される

 ➂initLoader()→forceLoad()を実施

 ④onLoadFinished()が2回呼び出される←!!?!?!??

 

解決方法

initLoadeをrestartLoaderに変更することで解決

 

なぜなのか

Android Developersによれば

Ensures a loader is initialized and active. If the loader doesn't already exist, one is created and (if the activity/fragment is currently started) starts the loader. Otherwise the last created loader is re-used.

In either case, the given callback is associated with the loader, and will be called as the loader state changes. If at the point of call the caller is in its started state, and the requested loader already exists and has generated its data, then callback onLoadFinished(Loader, D) will be called immediately (inside of this function), so you must be prepared for this to happen.

下記の条件を満たしていると、onLoadFinished()が即座に呼び出されるもよう。

 ・コールバックの呼び出し側が開始状態(?)にある。

 ・ローダーがすでに存在していて、データが生成されている。

 

つまり、2回目のinitLoader()呼び出し時には、下記の流れになるようだ。

①initLoader()実行

②onLoadFinished()が即座に呼び出される。

➂forceLoad()によって再度Loaderが動き、onLoadFinished()が呼び出される。