HQuser
HQuser

Reputation: 640

LiveData observeForever not working

I've a WeatherRepository class which calls the WeatherProvider class to start fetching the weather.

After the weather is successfully fetched, I simply post that weather using postValue function but the observer on that livedata in the WeatherRepository class's init block never gets called.

I am confused as what am I missing...

Any insights would be extremely helpful.

Here's my code for Repository and Provider:

class WeatherRepository @Inject constructor(private var weatherDao: WeatherDao, private var weatherProvider: WeatherProvider) {

    private fun startFetchWeatherService() {
        weatherProvider.startFetchWeatherService()
    }

    init {
        // Control flow always gets to this point
        var weather = weatherProvider.getDownloadedWeather()

        weather.observeForever { // This observer never gets called
            if (it != null) AsyncTask.execute { insertWeather(it) }

        }
        if (isFetchNeeded()) {
            startFetchWeatherService() // Android Studio always execute this line since no data is inserted by observer and fetch is needed
        }
    }
  ....
}


class WeatherProvider(private val context: Context) {
    private val mDownloadedWeather = MutableLiveData<List<Weather>>()
    ...

    fun getDownloadedWeather(): MutableLiveData<List<Weather>> = mDownloadedWeather

    fun getFromInternet() {
        ...
        call.enqueue(object : Callback<WorldWeatherOnline> {
          override fun onFailure(call: Call<WorldWeatherOnline>?, t: Throwable?) {} // TODO show error
          override fun onResponse(call: Call<WorldWeatherOnline>?, response: Response<WorldWeatherOnline>?) {
                if (response != null) {
                    val weather = response.body()?.data
                    if (weather != null) {
                      mDownloadedWeather.postValue(WeatherUtils.extractValues(weather)) // app always gets to this point and WeatherUtils successfully returns the List of weathers full of data
                    }
                }
            }
        })
    }

    fun startFetchWeatherService() {
        val intentToFetch = Intent(context, WeatherSyncIntentService::class.java)
        context.startService(intentToFetch)
    }
 }
    ...

// Dependency injection always works
// Here's my dagger2 module (other modules are very simillar to this one)
@Module
class ApplicationModule(private val weatherApplication: WeatherApplication) {
    @Provides
    internal fun provideWeatherApplication(): WeatherApplication {
        return weatherApplication
    }

    @Provides
    internal fun provideApplication(): Application {
        return weatherApplication
    }

    @Provides
    @Singleton
    internal fun provideWeatherProvider(context: WeatherApplication):   WeatherProvider {
        return WeatherProvider(context)
    }
}

@Singleton
class CustomViewModelFactory constructor(private val weatherRepository: WeatherRepository, private val checklistRepository: ChecklistRepository) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        when {
            modelClass.isAssignableFrom(WeatherViewModel::class.java) ->
                return WeatherViewModel(weatherRepository) as T
            modelClass.isAssignableFrom(ChecklistViewModel::class.java) ->
                return ChecklistViewModel(checklistRepository) as T
            else ->
                throw IllegalArgumentException("ViewModel Not Found")
        }
    }
}

class WeatherFragment : Fragment() {
    private lateinit var mWeatherModel: WeatherViewModel
    @Inject
    internal lateinit var viewModelFactory: ViewModelProvider.Factory

....
override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    mWeatherModel = ViewModelProviders.of(this, viewModelFactory)
            .get(WeatherViewModel::class.java)
...
    }
}

Upvotes: 2

Views: 5420

Answers (2)

Enzokie
Enzokie

Reputation: 7415

It is not necessary to change your postValue to setValue since it is done in a same Thread. The real issue here is the way how Dagger2 is supposed to be set.

In WeatherFragment.kt use

internal lateinit var viewModelFactory: CustomViewModelFactory

rather than

internal lateinit var viewModelFactory: ViewModelProvider.Factory

It is also necessary to add @Inject annotation in your CustomViewModelFactory.kt's constructor.

class CustomViewModelFactory @Inject constructor(

And lastly your WeatherProvider.kt is not in initialized state at all base on the code you provided. You can do it using this code :

    init {
        getFromInternet()
    }

Upvotes: 2

Bajrang Hudda
Bajrang Hudda

Reputation: 3268

Try to use

mDownloadedWeather.setValue(WeatherUtils.extractValues(weather))

instead of

mDownloadedWeather.postValue(WeatherUtils.extractValues(weather))

Because postValue() Posts a task to a main thread to set the given value. So if you have a following code executed in the main thread:

liveData.postValue("a");
liveData.setValue("b");

The value "b" would be set at first and later the main thread would override it with the value "a".

If you called this method multiple times before a main thread executed a posted task, only the last value would be dispatched.

Upvotes: 0

Related Questions