【问题标题】:Android Timber logging multiple timesAndroid Timber 多次记录
【发布时间】:2022-02-18 20:19:02
【问题描述】:

考虑以下简单设置。 1 个片段和 1 个 ViewModel:

片段

class TestFragment : Fragment() {

    private val viewModel by lazy {
        ViewModelProviders.of(this).get(TestViewModel::class.java)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_test, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel.testLiveData.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            Log.d("###", "whattt")
        })
    }
}

视图模型

class TestViewModel : ViewModel() {

    private val myVariable = Log.d("###", "Test")

    val testLiveData = MutableLiveData(false)
}

为什么我从 Fragment 和 ViewModel 都获得了最多 3 次的日志输出??

D/###: Test
D/###: whattt
D/###: Test
D/###: Test
D/###: whattt
D/###: whattt

【问题讨论】:

  • 这完全取决于你如何在代码中使用TestFragment
  • 很好的提示!我发现我的演示应用程序中的片段确实被初始化了 3 次。但在我的“真实”应用程序中,它没有......如果需要,我将进一步调查并更新问题。到目前为止谢谢!

标签: android kotlin android-architecture-components android-livedata android-viewmodel


【解决方案1】:

在@tynn 发表评论后,我意识到问题可能来自在片段实际涉及之前发生的一些操作。长话短说:我有一个多模块项目:1 个应用程序模块、1 个数据模块和 1 个网络模块。 网络模块和应用程序模块都在种植 Timber DebugTree...所以所有内容都记录了两次 facepalm

我搜索了一下,是否有一种在这方面保持模块独立的好方法。我唯一能找到的就是这个答案:

https://stackoverflow.com/a/53872754/990129

object TimberLogImplementation {

    fun initLogging() {
        if(Timber.treeCount() != 0) return
        if (BuildConfig.DEBUG) Timber.plant(DebugTree())
        else Timber.plant(ReleaseTree())
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    相关资源
    最近更新 更多