2017-10-09 217 views
1

我有一個運行架構組件的簡單應用程序。自從該庫(「Beta2」)的最新更新以來,我遇到了一個問題,我的observable沒有被觸發(在一個片段中,相同的代碼在一個Activity上運行)Android體系結構組件 - Observable not triggered

這是一個當前不工作的示例。

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

我錯過了什麼嗎?

感謝您的幫助。

+0

看看這可以幫助你:HTTPS:/ /stackoverflow.com/questions/45889604/livedata-is-not-updating-its-value-after-first-call – joao86

+0

謝謝。只要使用LifecycleFragment,它就會一直工作,但現在已經被棄用,它的邏輯已經轉移到片段(來自支持庫v26)我仍然有這個問題,雖然:( – colletjb

+0

我還沒有遷移到beta2,我會嘗試一下,看看我還在工作 – joao86

回答

0

我終於想出瞭解決上述問題的方法。

因爲我們在一個片段中,我必須使用活動來觀察。 (應該是「本」,但它至今沒有工作

isDataReady.observe(activity, Observer { 

我想這是一個臨時的解決辦法...

感謝您的幫助