LiveData observeForever无法正常工作

时间:2018-04-05 10:54:41

标签: android kotlin dagger-2 android-livedata

我有一个WeatherRepository类,它调用WeatherProvider类来开始获取天气。

成功获取天气后,我只是使用postValue函数发布该天气,但是WeatherRepository类的init块中的那个liveata上的观察者永远不会被调用。

我很困惑,因为我错过了......

任何见解都会非常有用。

这是我的存储库和提供商代码:

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)
...
    }
}

2 个答案:

答案 0 :(得分:1)

没有必要将postValue更改为setValue,因为它是在同一个帖子中完成的。这里真正的问题是如何设置Dagger2的方式。

WeatherFragment.kt 中使用

internal lateinit var viewModelFactory: CustomViewModelFactory

而不是

internal lateinit var viewModelFactory: ViewModelProvider.Factory

还需要在 CustomViewModelFactory.kt 的构造函数中添加@Inject注释。

class CustomViewModelFactory @Inject constructor(

最后, WeatherProvider.kt 根据您提供的代码完全没有处于初始化状态。您可以使用以下代码执行此操作:

    init {
        getFromInternet()
    }

答案 1 :(得分:0)

尝试使用

mDownloadedWeather.setValue(WeatherUtils.extractValues(weather))

而不是

mDownloadedWeather.postValue(WeatherUtils.extractValues(weather))

因为 postValue()将任务发布到主线程以设置给定值。因此,如果您在主线程中执行了以下代码:

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

价值&#34; b&#34;将首先设置,然后主线程将使用值&#34; a&#34;来覆盖它。

如果在主线程执行发布任务之前多次调用此方法,则只会调度最后一个值。