Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LiveData系列二——组件内使用observe是this还是getViewLifecycleOwner()? #63

Open
soapgu opened this issue Jul 14, 2021 · 0 comments
Labels
mvvm This issue or pull request already exists problem problem or trouble 安卓 安卓

Comments

@soapgu
Copy link
Owner

soapgu commented Jul 14, 2021

  • 问题由来

根据API文档,我们在Fragment里订阅LiveData通知,只要传入LifecycleOwner就行。

public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
        ViewModelStoreOwner, SavedStateRegistryOwner 

然后Fragment 是实现LifecycleOwner。那我应该这样就行

this.viewModel.getExitSignal().observe( this, exit -> {} );

但是我的Lint ,Android Studio爆红,出现error警告(虽然gradle build还是能过)
代码提示为Use getViewLifecycleOwner() as the LifecycleOwner.
再去看官网的sample

public class MyFragment extends Fragment {
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        StockLiveData.get(symbol).observe(getViewLifecycleOwner(), price -> {
            // Update the UI.
        });
    }
}

显然也是推荐是用getViewLifecycleOwner();

  • 疑惑???

为什么那,问号3连
图片

  1. 能用this解决问题为啥偏偏调getViewLifecycleOwner多此一举?
  2. 为什么Activity没有这个问题,可以直接用this?为啥Activity没有getViewLifecycleOwner这个方法?肯定不能用屁股决定脑袋因为没有getViewLifecycleOwner方法就只能用this牵强解释的。
  3. this和getViewLifecycleOwner究竟有什么区别,调用getViewLifecycleOwner的好处在哪里
  • 解答

翻了一圈官网没有给到我答案。最后博客里面找。

图片
从Fragment和Activity的生命周期的差异性来着手。

  • Activity 一生只会调用一次onCreate()和onDestroy()
  • Fragment 一生中可能会反复调用onCreateView() 和 onDestroyView()

然后再onCreate中调用observe,有什么坏处?文章里面说会造成Fragment跳转后收不到变化通知,我觉得文章这个表述是错误的(尽信书则不如无书)。因为LiveData明确了组件从休眠态到活跃态会收到相关通知的。

在onCreateView中调用observe,这样会造成多次订阅,这个理由成立。

另外在StackOverflow里面的一篇补充说明下

  • Use viewLifecycleOwner as the LifecycleOwner

  • viewLifecycleOwner is tied to when the fragment has (and loses) its UI (onCreateView(), onDestroyView())

  • this is tied to the fragment's overall lifecycle (onCreate(), onDestroy()), which may be substantially longer
    基本上make sence了

@soapgu soapgu added mvvm This issue or pull request already exists 安卓 安卓 problem problem or trouble labels Jul 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
mvvm This issue or pull request already exists problem problem or trouble 安卓 安卓
Projects
None yet
Development

No branches or pull requests

1 participant