2

Consider the following simple setup. 1 Fragment with 1 ViewModel:

Fragment

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")
        })
    }
}

ViewModel

class TestViewModel : ViewModel() {

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

    val testLiveData = MutableLiveData(false)
}

Why do I get a log output from both Fragment and ViewModel up to three times??

D/###: Test
D/###: whattt
D/###: Test
D/###: Test
D/###: whattt
D/###: whattt
muetzenflo
  • 5,653
  • 4
  • 41
  • 82
  • 1
    It completely depends on how you use `TestFragment` in your code. – tynn Jun 24 '19 at 07:54
  • Very good hint! i found out that the fragment in my demo app indeed gets initialized 3 times. But in my "real" app it does not...I will investigate further and update the question if need be. Thanks so far! – muetzenflo Jun 24 '19 at 18:31

1 Answers1

5

After the comment from @tynn I realized that the problem might come from some actions happening before the fragment actually is involved. Long story short: I have a multi-module project: 1 app module, 1 data module and 1 network module. Both the network module and the app module were planting a Timber DebugTree...So everything was logged twice facepalm

I searched a little bit if there is a good way to keep the modules independent in this regard. The only thing I could found was this SO answer:

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())
    }

}
muetzenflo
  • 5,653
  • 4
  • 41
  • 82