We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
根据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连
翻了一圈官网没有给到我答案。最后博客里面找。
从Fragment和Activity的生命周期的差异性来着手。
然后再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了
The text was updated successfully, but these errors were encountered:
No branches or pull requests
问题由来
根据API文档,我们在Fragment里订阅LiveData通知,只要传入LifecycleOwner就行。
然后Fragment 是实现LifecycleOwner。那我应该这样就行
但是我的Lint ,Android Studio爆红,出现error警告(虽然gradle build还是能过)
代码提示为Use getViewLifecycleOwner() as the LifecycleOwner.
再去看官网的sample
显然也是推荐是用getViewLifecycleOwner();
疑惑???
为什么那,问号3连
解答
翻了一圈官网没有给到我答案。最后博客里面找。
从Fragment和Activity的生命周期的差异性来着手。
然后再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了
The text was updated successfully, but these errors were encountered: