Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

android - Observing MediatorLiveData doesn't yeild any result (attached observer)

Basically, I am fetching the products list from this API using Retrofit into a MediatorLiveData inside ProductsRepository class. But, the problem is, when I try to observe the LiveData I get null.

Here is my code snippet:

ProductsRepository:

@MainScope
class ProductsRepository @Inject constructor(private val productsApi: ProductsApi) {

    private val products: MediatorLiveData<ProductsResource<List<ProductsModel>>> =
        MediatorLiveData()


    fun getProducts(): LiveData<ProductsResource<List<ProductsModel>>> {

        products.value = ProductsResource.loading(null)

        val source: LiveData<ProductsResource<List<ProductsModel>>> =
            LiveDataReactiveStreams.fromPublisher {

                productsApi.getProducts()
                    .onErrorReturn {
                        val p = ProductsModel()
                        p.setId(-1)
                        val products = ArrayList<ProductsModel>()
                        products.add(p)
                        products
                    }.map {
                        if (it[0].getId() == -1) {
                            ProductsResource.error("Something went wrong", null)
                        }
                        ProductsResource.success(it)
                    }.observeOn(Schedulers.io())
            }



        products.addSource(source){
            products.value = it
            products.removeSource(source)
        }

        return products

    }

} 

MainViewModel

class MainViewModel @Inject constructor(private val repository: ProductsRepository): ViewModel() {

    fun getProducts(): LiveData<ProductsResource<List<ProductsModel>>>{
        return repository.getProducts()
    }

}

MainActivity:

class MainActivity : DaggerAppCompatActivity() {

    lateinit var binding: ActivityMainBinding

    @Inject
    lateinit var viewModelProviderFactory: ViewModelProviderFactory

    lateinit var mainViewModel: MainViewModel

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

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initViewModel()

        subscribeToObservers()

    }

    private fun subscribeToObservers(){
        mainViewModel.getProducts()
            .observe(this){
                Log.d("", "subscribeToObservers: "+ it.data?.size)
            }
    }

    private fun initViewModel() {
        mainViewModel = ViewModelProvider(this, viewModelProviderFactory).get(MainViewModel::class.java)
    }

}

If I call hasActiveObservers(), it returns false although I am observing it from the MainActivity.

Now, let's say if I replace the MediatorLiveData with MutableLiveData and refactor my ProductsRepository like below, I get my expected output.

fun getProducts(): LiveData<ProductsResource<List<ProductsModel>>> {
    val products: MutableLiveData<ProductsResource<List<ProductsModel>>> = MutableLiveData()
    products.value = ProductsResource.loading(null)

    productsApi.getProducts()
        .onErrorReturn {
            //Log.d("MyError", it.message.toString())
            val p = ProductsModel()
            p.setId(-1)
            val product = ArrayList<ProductsModel>()
            product.add(p)
            product
        }.map { product ->
            if (product.isNotEmpty()) {
                if (product[0].getId() == -1) {
                   // Log.d("Map", "Error: ${product}")
                    ProductsResource.error(
                        "Something went Wrong",
                        null
                    )
                }
            }

            ProductsResource.success(product)

        }.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe {
            products.value = it
        }


    return products
}

I don't know If I am successful in explaining my problem. Please, let me know If I need to provide more details or code snippets.

Thanks in advance

question from:https://stackoverflow.com/questions/65839802/observing-mediatorlivedata-doesnt-yeild-any-result-attached-observer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...