Forum Xamarin.Forms

Add element to XAML page whiles in Task.Delay()

I'm building a chatbot app with chat bubbles for incoming and outgoing messages. For the incoming messages, I've given it a Task.Delay() and now I'd like to give it an ActivityIndicator every time before the message pops up (i.e. I want to show the activity indicator whiles the message is being delayed). I've added the activity indicator to the XAML of the incoming messages control;

IncomingMessageControlItem

<ViewCell
    x:Class="BluePillApp.Controls.IncomingMessageItemControl"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:pancake="clr-namespace:Xamarin.Forms.PancakeView;assembly=Xamarin.Forms.PancakeView"
    mc:Ignorable="d">


    <Grid x:Name="Gridoo">
        <pancake:PancakeView
            Margin="10,10,80,10"
            Padding="15"
            BackgroundColor="#53ffc6"
            CornerRadius="20,20,0,20"
            HasShadow="False"
            HorizontalOptions="StartAndExpand">

            <Label
                FontSize="Medium"
                Text="{Binding Text}"
                TextColor="#1a1a1a" />
        </pancake:PancakeView>

        <ActivityIndicator IsRunning="True" IsVisible="True" />
    </Grid>
</ViewCell>

The problem is, in the ChatbotMessagingPage, the send button is pressed then an outgoing message is sent before getting a reply/incoming message and I've done this in MVVM like so;

ChatbotMessagingPageViewModel

//This gets the chatbots response for each message
            chatbot.MainUser.ResponseReceived += async (sender, args) =>
            {
                await Task.Delay(1500);
                Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot });
            };
        }

        #region CLASS METHODS
        /// <summary>
        /// This function sends a message
        /// </summary>
        public void Send()
        {
            if (!string.IsNullOrEmpty(TextToSend))
            {
                var msgModel = new ChatMessageModel() { Text = TextToSend, User = App.User };

                //This adds a new message to the messages collection
                Messages.Add(msgModel);

                var result = chatbot.Evaluate(TextToSend);
                result.Invoke();

                //Removes the text in the Entry after message is sent
                TextToSend = string.Empty;
            }
        }

Everytime I press the send button the ActivityIndicator comes along with the IncomingMessage, I'd like the ActivityIndicator to come first, whiles the IncomingMessage is being delayed.

Answers

Sign In or Register to comment.