I am getting the compilation error invalid access of mutable storage in an 'isolated' function when attempting to update an array using an anonymous function with the forEach iterator.
The code:
isolated function searchEmailThread() returns string {
gmail:MailThread[] threads = [];
stream<gmail:MailThread,error?>|error threadList = gmail->listThreads(filter = {includeSpamTrash: false, labelIds: ["INBOX"]});
if (threadList is stream<gmail:MailThread,error?>) {
error? threadItr = threadList.forEach(isolated function (gmail:MailThread thread) {
lock {
threads.push(thread);
}
});
return threads.toString();
} else {
return "Failed to list threads";
}
}
The variable gmail:MailThread[] threads cannot be defined as isolated as well. Is there an alternative approach to obtain and return the mail threads from the stream?
>Solution :
threads is a captured variable for the argument function passed to forEach and for that function to be isolated, threads should either be final and have a type that is a subtype of readonly|isolated object {} or it should be an isolated variable.
Since none of that is possible here, you could rewrite this to use a query action (or a query expression).
error? res = from gmail:MailThread thread in threadList
do {
threads.push(thread);
};
Also related to https://github.com/ballerina-platform/ballerina-spec/issues/602
Only module-level variables can be defined as isolated variables at the moment (related spec issue).