Skip to content
New issue

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

MavericksView invalidate not being called #717

Open
Veeresh8 opened this issue Jun 4, 2024 · 2 comments
Open

MavericksView invalidate not being called #717

Veeresh8 opened this issue Jun 4, 2024 · 2 comments

Comments

@Veeresh8
Copy link

Veeresh8 commented Jun 4, 2024

This is my Activity where the ViewModel is being initiated

 class Dashboard : AppCompatActivity(), MavericksView {
  
    private val viewModel: DashboardViewModel by viewModel()
  
    override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      viewModel.fetchUsersList()
    }
  
    override fun invalidate() = withState(viewModel) { state ->
      println("State: $state")
    }
  }

This is my ViewModel

    data class DashboardState(val users: Async<List<String>> = Uninitialized) : MavericksState

    class DashboardViewModel
    @AssistedInject
    constructor(@Assisted initialState: DashboardState, private val userCase: Usecase) :
        MavericksViewModel<DashboardState>(initialState) {
    
      fun fetchUsersList() {
        suspend { userCase.getUsersList() }.execute {
            println("Users: $it")
            copy(users = it)
        }
      }

    @AssistedFactory
    interface Factory : AssistedViewModelFactory<DashboardViewModel, DashboardState> {
      override fun create(state: DashboardState): DashboardViewModel
    }
  
    companion object :
        MavericksViewModelFactory<
            DashboardViewModel, DashboardState> by hiltMavericksViewModelFactory()
  }

The use-case

class Usecase @Inject constructor() {

suspend fun getUsersList(): List<String> {
    delay(2000)
    return listOf("A", "B", "C")
    }
}

However, invalidate is never called in my case, not sure why this is happening.
I noticed that when I use the same logic in a fragment using fragmentViewModel it works for me.

@ldw5821cn
Copy link

activityViewModel() is designed to get an activity scoped view model from a Fragment. You want just by viewModel()
However, I recommend using Fragments. Putting UI directly inside of an Activity is no longer recommended in general for Android.

@ldw5821cn
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants