Hello, I've a question. How can I use break keywor...
# android
h
Hello, I've a question. How can I use break keyword in LiveData observer?
Copy code
for (i in 0 until domainList.size) {

    mainViewModel.fetchVbtopUrls(concatenated)
    mainViewModel.vbtopurl.observe(this, { it2 ->

        when (it2.status) {
            Status.SUCCESS -> {
              
                if (it2.data != null) {
                
                    break   //error
                }
            }

        }
    })
 
}
j
You could
Copy code
return@observe
wouldn’t that achieve the same effect?
h
@Jiddles Thanks for your reply. But it doesn't help, the app crashes.
j
Im not sure that’s caused by the return itself 🤔 What’s the exception/crash message?
h
When I use return@observe, it doesn't exist from loop and the app crashes, but doesn't show error message.
g
you're mixing 2 behaviour here, for loop is sync, observe is async, the loop is ended way before an event is possibly received in the observe callback
j
If you’re using Android studio, you can find logcat . A fatal exception that crashes the app, will always have the word
Fatal
so you can use the search bar to find it But @Grégory Lureau is probably correct about the issue here
h
@Grégory Lureau Thanks for your reply. You can see the code more. I want to say that 'break' works in for(){}, but in if(){} doesn't work.
Copy code
mainViewModel.urls.observe(this, { it1 ->


    when (it1.status) {
        Status.SUCCESS -> {
            progressbar.visibility = View.GONE
           

            if (partnerName == it1.data.Name) {
                for (i in 0 until domainList.size) {
                    mainViewModel.fetchVbtopUrls(concatenated)
                    mainViewModel.vbtopurl.observe(this, { it2 ->

                        when (it2.status) {
                            Status.SUCCESS -> {

                                if(it2.data!=null){
                                    break  //error
                                }

                            }
                      
                        }
                    })
                }
            }
        }

        Status.ERROR -> {
            progressbar.visibility = View.GONE
            Toast.makeText(this, it1.message, Toast.LENGTH_LONG).show()
        }
    }
})
g
You're observing in an observe callback, not even sure what's going on here. When you call
viewmodel.stuff.observe(..,  { doStuff() })
the doStuff is executed as a callback. It means it's not in the for loop, it can be called after some time. Each time urls changes, you attach multiple observers on vbtopurl, each will triggers (possibly multiple times) the second callback (with it2), but you actually observing the same stream. Globally it makes little sense to me.