Masksway
Masksway

Reputation: 225

How to render view before making database call using kotlin

I have weird issue with (probably? I haven't had this problem before) koin.

I am using a combination of Flow(from dao to view model) and LiveData(from view model to fragment)

My repository looking like this:

fun getPets(): Flow<Status> = flow { 
    
    emit(Status.LOADING)
    
    SystemClock.sleep(5000)
    
    emit(Status.PETS(petsDao.getPets()))
    
}

In my fragment I'm instantiate my view model using Koin like this:

private val petsViewModel: PetsViewModel by viewModel()

And observe the data like this:

 petsViewModel.status.observe(viewLifecycleOwner, Observer {status ->
        
        if (status == LOADING) {
            uiListener.displayProgressBar(true)
        } else if(status == PETS) {
            //Show pets data
        }
 
    })

Koin view model setup:

  viewModel {
           PetsViewModel(
                petsRepository = get(),
                context = androidContext()
            )
        }

The problem is when I launch the app I am getting Status.Loading but without any view.

and when the status changes to Staus.PETS I am getting the pets data and the view.

It's like the view model is too fast and it's calling to repository before I even have a chance to inflate the view(I logged the lifecycle and it does call before onResume)

How can I fix my code?

Upvotes: 0

Views: 305

Answers (1)

Ali
Ali

Reputation: 529

In my opinion, instead of using sleep(blocking method) which instead of doing the work will just block the execution, you should use custom callbacks

  1. for checking if the view has been inflated or not, try finding a view if returns null then the view has not yet been inflated else it has been inflated

findViewById(your_view_id)

  1. if the view != null then do execute the callback like this.

I've been in similar problems and custom callbacks were the solution. if you need any further help with the custom callbacks please let me know I'll update my answer and come up with a practical example.

Upvotes: 1

Related Questions