Search code examples
androidobservablelifecycleandroid-architecture-components

Android Architecture Components - Observable not triggered


I've a simple application running Architecture Components. Since the latest update of the library ("Beta2"), i've an issue with my observable not being triggered (in a Fragment, the same code works on an Activity)

Here is a sample which is currently not working.

class SampleFragment : Fragment() {

    private var isDataReady = MutableLiveData<Boolean>()

    private val registry = LifecycleRegistry(this)

    override fun getLifecycle(): LifecycleRegistry = registry

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_main2, container, false)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        fab.setOnClickListener { _ ->
            isDataReady.postValue(true)
        }
        isDataReady.observe(this, Observer {
            Snackbar.make(fab, "Hello!", Snackbar.LENGTH_LONG).show()
        })
    }
}

Did i missed something ?

Thanks for your help.


Solution

  • I've finally figured out a solution on the above issue.

    As we are in a Fragment, i must use the Activity to observe. (It should be "this" but it's not working so far.

    isDataReady.observe(activity, Observer {
    

    I guess it's a temporary fix...

    Thanks for your help