Scoping a viewmodel to multiple fragments (not activity) using the navigation component

前端 未结 3 1791
北荒
北荒 2020-12-05 19:24

I\'m using the navigation component, I want a view model to be shared between a few fragments but they should be cleared when I leave the fragments (hence not scoping them t

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 20:08

    Yes, it's possible to scope a viewmodel to a navgraph now starting with androidx.navigation:*:2.1.0-alpha02. See the release notes here and an example of the API here. All you need to give is the R.id for your navgraph. I find it a bit annoying to use, though, because normally viewmodels are initialized in onCreate, which isn't possible with this scope because the nav controller isn't guaranteed to be set by your nav host fragment yet (I'm finding this is the case with configuration changes).

    Also, if you don't want your mainFragment to be part of that scope, I would suggest taking it out and maybe using a nested nav graph.

提交回复
热议问题