I have this code in my view model
class SearchViewModel #ViewModelInject constructor(jobUseCase: JobUseCase) : ViewModel() {
val job = jobUseCase.getSearchJob(...).asLiveData()
}
but thegetSearchJob() need the parameter to fill. and this where I use the job in the activity
private fun getSearchData() {
searchViewModel.job.observe(this, { job ->
if (job != null) {
when (job) {
is Resource.Loading -> binding.progressBar.visibility = View.VISIBLE
is Resource.Success -> {
binding.progressBar.visibility = View.GONE
jobAdapter.setData(job.data)
}
is Resource.Error -> {
binding.progressBar.visibility = View.GONE
}
}
}
})
}
but I don't know how to fill the getSearchJob() parameter in the val. or if there is any idea please help me.
I think it would be simpler for you to have a simple MutableLiveData instance, from which you can expose a regular liveData that can be exposed to the activity, and a onTextChanged Listener simply updates the viewModel, jobUseCase.getSearchJob(...) gets the data, and then you can set the new value to MutableLiveData instance.
if you need something more elegant, then let jobUseCase.getSearchJob(...) take in a flow instance that you can pass in data to which in turn fires off your job livedata
Simple Mutable livedata based example
class SearchViewModel1 constructor(private val jobUseCase: JobUseCase) : ViewModel() {
private val _internalMutableLiveData = MutableLiveData<String>()
private val publicLiveData: LiveData<String> = _internalMutableLiveData
fun updateSearchTerm(term: String) {
viewModelScope.launch {
val result = jobUseCase.getSearchJob(term)
_internalMutableLiveData.value = result
}
}
}
class JobUseCase {
suspend fun getSearchJob(term: String): String {
// fetch Data here
return ""
}
}
Related
I have the following:
interface CartRepository {
fun getCart(): Flow<CartState>
}
interface ProductRepository {
fun getProductByEan(ean: String): Flow<Either<ServerError, Product?>>
}
class ScanViewModel(
private val productRepository: ProductRepository,
private val cartRepository: CartRepository
) :
BaseViewModel<ScanUiState>(Initial) {
fun fetchProduct(ean: String) = viewModelScope.launch {
setState(Loading)
productRepository
.getProductByEan(ean)
.combine(cartRepository.getCart(), combineToGridItem())
.collect { result ->
when (result) {
is Either.Left -> {
sendEvent(Error(R.string.error_barcode_product_not_found, null))
setState(Initial)
}
is Either.Right -> {
setState(ProductUpdated(result.right))
}
}
}
}
}
When a user scans a barcode fetchProduct is being called. Every time a new coroutine is being set up. And after a while, there are many running in the background and the combine is triggered when the cart state is updated on all of them, which can cause errors.
I want to cancel all old coroutines and only have the latest call running and update on cart change.
I know I can do the following by saving the job and canceling it before starting a new one. But is this really the way to go? Seems like I'm missing something.
var searchJob: Job? = null
private fun processImage(frame: Frame) {
barcodeScanner.process(frame.toInputImage(this))
.addOnSuccessListener { barcodes ->
barcodes.firstOrNull()?.rawValue?.let { ean ->
searchJob?.cancel()
searchJob = viewModel.fetchProduct(ean)
}
}
.addOnFailureListener {
Timber.e(it)
messageMaker.showError(
binding.root,
getString(R.string.unknown_error)
)
}
}
I could also have a MutableSharedFlow in my ViewModel to make sure the UI only react to the last product the user has been fetching:
private val productFlow = MutableSharedFlow<Either<ServerError, Product?>>(replay = 1)
init {
viewModelScope.launch {
productFlow.combine(
mycroftRepository.getCart(),
combineToGridItem()
).collect { result ->
when (result) {
is Either.Right -> {
setState(ProductUpdated(result.right))
}
else -> {
sendEvent(Error(R.string.error_barcode_product_not_found, null))
setState(Initial)
}
}
}
}
}
fun fetchProduct(ean: String) = viewModelScope.launch {
setState(Loading)
repository.getProductByEan(ean).collect { result ->
productFlow.emit(result)
}
}
What's considered best practice handling this scenario?
I can't think of a simpler pattern for cancelling any previous Job when starting a new one.
If you're concerned about losing your stored job reference on screen rotation (you probably won't since Fragment instances are typically reused on rotation), you can move Job storage and cancellation into the ViewModel:
private var fetchProductJob: Job? = null
fun fetchProduct(ean: String) {
fetchProductJob?.cancel()
fetchProductJob = viewModelScope.launch {
//...
}
}
If you're repeatedly using this pattern, you could create a helper class like this. Not sure if there's a better way.
class SingleJobPipe(val scope: CoroutineScope) {
private var job: Job? = null
fun launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job = synchronized(this) {
job?.cancel()
scope.launch(context, start, block).also { job = it }
}
}
// ...
private val fetchProductPipe = SingleJobPipe(viewModelScope)
fun fetchProduct(ean: String) = fetchProductPipe.launch {
//...
}
I think my observable is set incorrectly here. I am using Retrofit2 + Moshi as the deserializer, and the API call from Retrofit is working.
But once I make the API call, I am trying to set up the Observable in my Activity and then use the API call data from the data class.
Here is my view model code:
class DealsViewModel(val repository: MainRepository) : ViewModel() {
val movieList = MutableLiveData<List<DealItems>>()
var job: Job? = null
val loading = MutableLiveData<Boolean>()
val errorMessage = MutableLiveData<String>()
val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
onError("Exception handled: ${throwable.localizedMessage}")
}
fun getMovies() {
viewModelScope.launch{
// View Model Scope gives the Coroutine that will be canceled when the ViewModel is cleared.
job = CoroutineScope(Dispatchers.IO + exceptionHandler).launch {
val items = repository.getProduct()
withContext(Dispatchers.Main) {
if (items.isNullOrEmpty()) {
loading.value = false
// put error message in here later
} else {
dealList.postValue(items)
return#withContext
}
}
}
}
}
private fun onError(message: String) {
errorMessage.value = message
loading.value = false
}
override fun onCleared() {
super.onCleared()
job?.cancel()
}
}
And here is my MainActivity code.
I am using JetpackCompose in my activity, LiveData for the API response container. In my main repository is where I am validating a successful API response and then the coroutines for the call are inside of the view model.
My API call is successful, but I am not sure where to call the ViewModel.GetMovies() inside of the activity and I am not sure if the observables are set properly and/or where to pass the API's livedata into my composable function.
Thanks for any help you can provide. I am new to android and trying to use Coroutines for the first time.
class MainActivity: ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val retrofitService = RetrofitService.getInstance()
val viewModel = ViewModelProvider(this,
MyViewModelFactory(MainRepository(retrofitService = retrofitService))).get(DealsViewModel::class.java)
// viewModel.getProducts()
setContent {
myApp {
MyScreenContent()
}
viewModel.movieList.observe(
this, { it ->
if( it != null) {
it.forEach {
var movieLocation = it.movieLocation
val description = it.description
val id = it.id
val title = it.title
val regularPrice = it.regularPrice
}
}
})
return#setContent
}
viewModel.errorMessage.observe(this, {
Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
})
viewModel.loading.observe(
this,
Observer {
if (it) {
}
})
}
}
I assume that it always depends when should you call especially in the activity we have many lifecycles; however, the best way is to use the .also on the livedata/stateflow lazy creation so that you do guarantee as long as the view model is alive, the getMovies is called only one time, and also guarantee the service itself is not called unless someone is listening to it.
You may check the full documentation in this link
Here is a code example
class MyViewModel : ViewModel() {
private val users: MutableLiveData<List<User>> by lazy {
MutableLiveData<List<User>>().also {
loadUsers()
}
}
fun getUsers(): LiveData<List<User>> {
return users
}
private fun loadUsers() {
// Do an asynchronous operation to fetch users.
}
}
When using this code, you do not have to call getMovies at all in the activity, you just listen to the observer.
So I'm trying to implement mvvm architecture with navigation component, this code snipet works just fine.. the problem is that when I navigate from fragmentA to FragmentB there is no way to go back to FragmentA, its like the button is blocked (If I remove the ViewModel the navigation works fine so it has something to do with the ViewModel).
anyone have an idea of whats happening?
private fun initVewModel() {
myViewModel = MyViewModel()
myViewModel = ViewModelProviders
.of(this, createFor(myViewModel))
.get(MyViewModel::class.java)
}
private fun setupObservers() {
myViewModel.myData.observe(viewLifecycleOwner, Observer {
it?.let { resource ->
when (resource.status) {
Status.SUCCESS -> {
resource.data?.let {
val action =
FragmentADirections.actionFragmentAToFragmentB()
Navigation.findNavController(requireView()).navigate(action)
}
}
Status.ERROR -> {
//TODO show an error
loading.visibility = View.GONE
}
Status.LOADING -> {
loading.visibility = View.VISIBLE
}
}
}
})
}
This is my ViewModel
class MyViewModel : ViewModel() {
private val searchText = MutableLiveData<String>()
//This method is called on a search button click
fun setSearchText(text: String) {
searchText.value = text
}
val myData = searchText.switchMap { text ->
liveData(Dispatchers.IO) {
emit(Resource.loading(data = null))
try {
emit(Resource.success(data = dataOrigin.getData(text)))
} catch (exception: Exception) {
exception.printStackTrace()
emit(Resource.error(data = null, message = exception.message ?: "Error Occurred!"))
}
}
}
}
That's because your myData Observer will be immediately triggered with the latest data on back navigation and trigger the SUCCESS branch once again.
I recommend either using SharedFlows or checking out a SingleLiveEvent pattern for LiveData, where you can only consume an event once.
UPDATE:
A possible solution for the consumable pattern:
class Consumable<T>(private val event: T) {
private var isConsumed = false
fun consume(): T? {
if (isConsumed) return null
isConsumed = true
return event
}
fun peek() = event
}
Then in the ViewModel:
val event = MutableLiveData<Consumable<YourEventClass>>()
...
event.value = Consumable(XYEvent)
And you'd observe it like this:
viewModel.event.observe{ event ->
event.consume()?.let{
// Do your navigation here
}
}
Additionally you could write an extension function .consume(), for consumable livedatas, which unwraps the value
I have a repository setup like this
class ServerTimeRepo #Inject constructor(private val retrofit: Retrofit){
var liveDataTime = MutableLiveData<TimeResponse>()
fun getServerTime(): LiveData<TimeResponse> {
val serverTimeService:ServerTimeService = retrofit.create(ServerTimeService::class.java)
val obs = serverTimeService.getServerTime()
obs.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).unsubscribeOn(Schedulers.io())
.subscribe(object : Observer<Response<TimeResponse>> {
override fun onComplete() {
}
override fun onSubscribe(d: Disposable) {
}
override fun onNext(t: Response<TimeResponse>) {
val gson = Gson()
val json: String?
val code = t.code()
val cs = code.toString()
if (!cs.equals("200")) {
json = t.errorBody()!!.string()
val userError = gson.fromJson(json, Error::class.java)
} else {
liveDataTime.value = t.body()
}
}
override fun onError(e: Throwable) {
}
})
return liveDataTime
}
}
Then I have a viewmodel calling this repo like this
class ServerTimeViewModel #Inject constructor(private val serverTimeRepo: ServerTimeRepo):ViewModel() {
fun getServerTime(): LiveData<TimeResponse> {
return serverTimeRepo.getServerTime()
}
}
Then I have an activity where I have an onClickListener where I am observing the livedata, like this
tvPWStart.setOnClickListener {
val stlv= serverTimeViewModel.getServerTime()
stlv.observe(this#HomeScreenActivity, Observer {
//this is getting called multiple times??
})
}
I don't know what's wrong in this. Can anyone point me in the right direction? Thanks.
Issue is that every time your ClickListener gets fired, you observe LiveData again and again. So, you can solve that problem by following solution :
Take a MutableLiveData object inside your ViewModel privately & Observe it as LiveData.
class ServerTimeViewModel #Inject constructor(private val serverTimeRepo: ServerTimeRepo):ViewModel() {
private val serverTimeData = MutableLiveData<TimeResponse>() // We make private variable so that UI/View can't modify directly
fun getServerTime() {
serverTimeData.value = serverTimeRepo.getServerTime().value // Rather than returning LiveData, we set value to our local MutableLiveData
}
fun observeServerTime(): LiveData<TimeResponse> {
return serverTimeData //Here we expose our MutableLiveData as LiveData to avoid modification from UI/View
}
}
Now, we observe this LiveData directly outside of ClickListener and we just call API method from button click like below :
//Assuming that this code is inside onCreate() of your Activity/Fragment
//first we observe our LiveData
serverTimeViewModel.observeServerTime().observe(this#HomeScreenActivity, Observer {
//In such case, we won't observe multiple LiveData but one
})
//Then during our ClickListener, we just do API method call without any callback.
tvPWStart.setOnClickListener {
serverTimeViewModel.getServerTime()
}
I'm in the process of wrapping my head around Architecture Components / MVVM.
Let's say I have a repository, a ViewModel and a Fragment. I'm using a Resource class as a wrapper to expose network status, like suggested in the Guide to architecture components.
My repository currently looks something like this (simplified for brevity):
class MyRepository {
fun getLists(organizationId: String) {
var data = MutableLiveData<Resource<List<Something>>>()
data.value = Resource.loading()
ApolloClient().query(query)
.enqueue(object : ApolloCall.Callback<Data>() {
override fun onResponse(response: Response<Data>) {
response.data()?.let {
data.postValue(Resource.success(it))
}
}
override fun onFailure(exception: ApolloException) {
data.postValue(Resource.exception(exception))
}
})
}
Then in the ViewModel, I also declare a MutableLiveData:
var myLiveData = MutableLiveData<Resource<List<Something>>>()
fun getLists(organizationId: String, forceRefresh: Boolean = false) {
myLiveData = myRepository.getLists(organizationId)
}
Finally, the Fragment:
viewModel.getLists.observe(this, Observer {
it?.let {
if (it.status.isLoading()) showLoading() else hideLoading()
if (it.status == Status.SUCCESS) {
it.data?.let {
adapter.replaceData(it)
setupViews()
}
}
if (it.status == Status.ERROR) {
// Show error
}
}
})
As you see, there will be an issue with the observer not being triggered, since the LiveData variable will be reset in the process (the Repository creates a new instance).
I'm trying to figure out the best way to make sure that the same LiveData variable is used between the Repository and ViewModel.
I thought about passing the LiveData from the ViewModel to the getLists method, so that the Repository would be using the object from the ViewModel, but even if it works, it seems wrong to do that.
What I mean is something like that:
ViewModel
var myLiveData = MutableLiveData<Resource<List<Something>>>()
fun getLists(organizationId: String, forceRefresh: Boolean = false) {
myRepository.getLists(myLiveData, organizationId)
}
Repository
fun getLists(data: MutableLiveData<Resource<List<Something>>>, organizationId: String) {
...
}
I think I figured out how to do it, thanks to #NSimon for the cue.
My repository stayed the same, and my ViewModel looks like this:
class MyViewModel : ViewModel() {
private val myRepository = MyRepository()
private val organizationIdLiveData = MutableLiveData<String>()
private val lists = Transformations.switchMap(organizationIdLiveData) { organizationId -> myRepository.getLists(organizationId) }
fun getLists() : LiveData<Resource<MutableList<Something>>> {
return lists
}
fun fetchLists(organizationId: String, forceRefresh: Boolean = false) {
if (organizationIdLiveData.value == null || forceRefresh) {
organizationIdLiveData.value = organizationId
}
}
}
I observe getLists() in my fragment, and call viewModel.fetchLists(id) when I want the data. Seems legit?