0

I have a single activity app and have the next problem. One of my screens (let's call it fragment A) has small viewpager (about half of the fragments' A size) with 2 fragments: B and C. The content of fragment B and C depends on content of A because it's dynamic. Fragment A has viewModel which has some id which I need to use in Fragment B. So I want to use sharedviewmodel to get this value as below: Fragment A:

viewModel.loadData()

Fragment B:

viewModel.observesomedata.observe(...)

So the problem is when initializing SharedViewModel in Fragment B, compiler says that "lazy value not initialized yet" Any suggestions?

Zhandr
  • 137
  • 1
  • 7
  • Why not initialize the data in the ViewModel's `init` block? Then you don't have to depend on calling some `loadData()` function or have to use `lateinit var`s. – Tenfour04 Nov 12 '20 at 20:08
  • @Tenfour04 can you provide some example please? I jsut cant get your answer – Zhandr Nov 12 '20 at 20:12
  • Does this answer your question? [Sharing data between fragments using new architecture component ViewModel](https://stackoverflow.com/questions/44272914/sharing-data-between-fragments-using-new-architecture-component-viewmodel) – cutiko Nov 12 '20 at 20:45
  • I'm suggesting moving the content of your `loadData()` function into the initialization block (constructor) of your ViewModel class so it's guaranteed to always be loaded. If you want the same instance of your ViewModel to be shared by all your fragments, use `by activityViewModels()` instead of `by viewModels()` to get your reference. The activity doesn't have to know about it, but all the fragments are using the activity to get the same view model instance. – Tenfour04 Nov 12 '20 at 20:57
  • https://developer.android.com/topic/libraries/architecture/viewmodel#sharing – Tenfour04 Nov 12 '20 at 20:58
  • @Tenfour4 how can i use it with koin? – Zhandr Nov 12 '20 at 22:04

0 Answers0