Getting Error while testing LiveData observer in AndroidTest : java.lang.IllegalStateException: Cannot invoke observeForever on a background thread - android-livedata

Here tried running this code but returns above error when used any Dispatcher(Main, IO) on runTest, runBlockingTest. Only using runBlocking returns Different Error LiveData Value TimeOut error, Value is never set.
fun checkIfStringTranslated() {
val translateString = TranslateString("मेरा नाम नवनीत हैं।", "", TranslateLanguage.ENGLISH)
val translatedLiveData = translateString.getTranslation()
testScope.runTest {
Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler))
try{ val result = translatedLiveData.getOrAwaitValue()
assertThat(result).isEqualTo("My name is ")
}finally {
Dispatchers.resetMain()
}
}}
This TranslateString.getTranslation() observes liveData of translatedText from MLkit translate.

Related

Orchestrator function code awaits on a task that was not created by a DurableOrchestrationContext method

I have the following code in Orchestrator function:
var sourceGroups = await context.CallActivityAsync<AzureADGroup[]>(nameof(SourceGroupsReaderFunction), new SourceGroupsReaderRequest { SyncJob = syncJob, RunId = runId });
if (sourceGroups.Length == 0)
{
await _log.LogMessageAsync(new LogMessage
{
RunId = runId,
Message =
$"None of the source groups in {syncJob.Query} were valid guids. Marking job as errored."
});
await _calculator.SendEmailAsync(syncJob, runId, SyncDisabledNoValidGroupIds, new[] { syncJob.Query });
}
On running this, I see the following error:
Function 'OrchestratorFunction (Orchestrator)' failed with an error. Reason: System.InvalidOperationException: Multithreaded execution was detected. This can happen if the orchestrator function code awaits on a task that was not created by a DurableOrchestrationContext method. More details can be found in this article https://learn.microsoft.com/en-us/azure/azure-functions/durable-functions-checkpointing-and-replay#orchestrator-code-constraints.
What am I missing?

How to do error handling for GraphQL server using FSharp.Data.GraphQL in F#?

I am using FSharp.Data.GraphQL for implementing GraphQL server. The documentation is not very clear about error handling. In the following mutation resolver, I wish to return errors if user provides invalid values for email and password:
let login =
Define.AsyncField(
name = "login",
typedef = Nullable Output.Token,
description = "Login using email and password",
args = [
Define.Input("email", String)
Define.Input("password", String)
],
resolve =
fun ctx _ ->
// ... some more code related to db and validation
let customErr: exn = Error.InvalidUserPassword
// This statement has not effect
ctx.AddError customErr
// Should I use raise to explicitly throw exception
// raise customErr
Async.result None
)
Looking into the source code, I found out AddError method on ResolveFieldContext. But it seems to produce no effect on the final result of the mutation. The output is always without any error:
{
"documentId": 1234,
"data": {
"login": null
},
// The errors array is not available
"errors": []
}
Should I raise the exception to add the error handling? And, if that is the case, how can I go about adding multiple error codes as part of single query or mutation since I can raise only one exception?

How catch exception using Iteratee.foreach in Future

I'm using Play Framework 2.2 and ReactiveMongo. I'm iterating trough all received entries from ReactiveMongo, and getting some property from single entry. Sometimes it throws Exception of inexistent property, how should I catch it, for now using simple "recover" doesn't work.
val cursor:Cursor[JsObject] = // QUERY FOR DATA
val processingData = cursor.enumerate().apply(Iteratee.foreach { doc =>
(doc \ "property")
}
processingData.map { data =>
Logger.info(s"$data")
None
}.recover {
case e =>
Logger.error(s"Error during parsing $e")
None
}
Iteratee.foreach always return Unit type, so value processingData will not contain data and enumerator apply some Iteratee only attach iteratee to emumerator, but don't run it. I think, this must solve your problem:
val cursor:Cursor[JsObject] = // QUERY FOR DATA
val getData = Enumeratee.mapM[JsObject]{doc =>
Future(doc \ "property") //use future to catch exception here
}
val processingData: Future[scala.List[JsObject]] = cursor.enumerate() &> getData .run Iteratee.getChunks

run something async in Grails 2.3

In My Grails service, there is a part of a method I wish to run asynchronously.
Following, the doc for 2.3.x http://grails.org/doc/2.3.0.M1/guide/async.html
I do
public class MyService {
public void myMethod() {
Promise p = task {
// Long running task
}
p.onError { Throwable err ->
println "An error occured ${err.message}"
}
p.onComplete { result ->
println "Promise returned $result"
}
// block until result is called
def result = p.get()
}
}
However, I want to execute mine without any blocking. The p.get() method blocks. How do I execute the promise without any sort of blocking. I don't care if myMethod() returns, it is a kinda of fire and forget method.
So, according to the documentation if you don't call .get() or .waitAll() but rather just make use of onComplete you can run your task without blocking the current thread.
Here is a very silly example that I worked up in the console to as a proof of concept.
import static grails.async.Promises.*
def p = task {
// Long running task
println 'Off to do something now ...'
Thread.sleep(5000)
println '... that took 5 seconds'
return 'the result'
}
p.onError { Throwable err ->
println "An error occured ${err.message}"
}
p.onComplete { result ->
println "Promise returned $result"
}
println 'Just to show some output, and prove the task is running in the background.'
Running the above example gives you the following output:
Off to do something now ...
Just to show some output, and prove the task is running in the background.
... that took 5 seconds
Promise returned the result

Grails async - creating promises

I am in grails 2.3.1 - trying to use the async features.
This is bulk data processing. I am trying to synchronise 2 databases, which involves comparing both and returning a list of 'deltas'. I am trying to speed up the process
The documentation says I can just add a set of closures to a PromiseList and then call onComplete() to check that all the closures have completed. These are my attempts - directly building on "You can also construct a PromiseList manually" in the documentation:
def tasksMemberDeltas = new PromiseList()
pages.each {Integer page ->
tasksMemberDeltas << {findCreateMemberDeltas(page, (page + pageSize) - 1)}
if (page % 30 == 0) {
tasksMemberDeltas.onComplete {
tasksMemberDeltas = new PromiseList()
}
}
Returns:
Error groovy.lang.MissingMethodException:
No signature of method: java.util.ArrayList.onComplete()
In the end I called .get() which calls waitAll. Going into .get() and finding that it did waitAll was my revelation.
So if I have a single task I call:
waitAll finalDeltas
If I have a list I call:
taskFinalDeltas.get()
onComplete() logically relates to a single delta. Not the list. So this works OK:
Promise memberDeleteDeltas = task {
findDeleteAndTagDeltas()
}
memberDeleteDeltas.onError { Throwable err ->
println "An error occured ${err.message}"
}
memberDeleteDeltas.onComplete { result ->
println "Completed create deltas"
}
waitAll(memberDeleteDeltas)

Resources